From 30b2803dd3f556e3af09708b8c9f432701b0117b Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 20:30:23 +0530 Subject: [PATCH 01/14] fix: maxRetries was empty string and didn't default --- dist/index.js | 1581 +++++++++++++++++++++++++------------------------ index.js | 23 +- 2 files changed, 805 insertions(+), 799 deletions(-) diff --git a/dist/index.js b/dist/index.js index 0593143..f633a6e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -111401,797 +111401,800 @@ function zodResponsesFunction(options) { // EXTERNAL MODULE: ./node_modules/micromatch/index.js var micromatch = __nccwpck_require__(8785); ;// CONCATENATED MODULE: ./utils/types.js - - -const aDiff = z.object({ - path: z.string(), - position: z.number(), - line: z.number(), - change: z.object({ - type: z.string(), - add: z.boolean(), - ln: z.number(), - content: z.string(), - relativePosition: z.number(), - }), - previously: z.union([z.string(), z.null()]), - suggestions: z.union([z.string(), z.null()]), -}); - -const diffPayloadSchema = z.object({ - commentsToAdd: z.array(aDiff), -}); - -const diffPayloadSchemaWithRequiredSuggestions = diffPayloadSchema.extend({ - commentsToAdd: z.array(aDiff.extend({ suggestions: z.string() })), -}); - - + + +const aDiff = z.object({ + path: z.string(), + position: z.number(), + line: z.number(), + change: z.object({ + type: z.string(), + add: z.boolean(), + ln: z.number(), + content: z.string(), + relativePosition: z.number(), + }), + previously: z.union([z.string(), z.null()]), + suggestions: z.union([z.string(), z.null()]), +}); + +const diffPayloadSchema = z.object({ + commentsToAdd: z.array(aDiff), +}); + +const diffPayloadSchemaWithRequiredSuggestions = diffPayloadSchema.extend({ + commentsToAdd: z.array(aDiff.extend({ suggestions: z.string() })), +}); + + ;// CONCATENATED MODULE: ./utils/constants.js -const DEFAULT_MODEL = { - OPENAI: { - name: "gpt-4o-2024-08-06", - }, - ANTHROPIC: { - name: "claude-3-7-sonnet-latest", - }, - MISTRAL: { - name: "pixtral-12b-2409", - }, - OPENROUTER: { - name: "deepseek/deepseek-r1", - }, - GOOGLE: { - name: "gemini-2.5-pro-preview-05-06", - }, -}; - -const BASE_URL = { - OPENROUTER: "https://openrouter.ai/api/v1", - GOOGLE: "https://generativelanguage.googleapis.com/v1beta/openai/", -}; - -const COMMON_SYSTEM_PROMPT = ` - You are a highly experienced software engineer and code reviewer with a focus on code quality, maintainability, and adherence to best practices. - Your goal is to provide thorough, constructive, and actionable feedback to help developers improve their code. - You consider various aspects, including readability, efficiency, and security. - The user will provide you with a diff payload of a pull request and some rules on how the code should be (they are separated by --), and you have to make suggestions on what can be improved by looking at the diff changes. You might be provided with a pull request description for more context (most probably in markdown format). - Take the user input diff payload and analyze the changes from the "content" property (ignore the first "+" or "-" character at the start of the string because that's just a diff character) of the payload and suggest some improvements (if an object contains "previously" property, compare it against the "content" property and consider that as well to make suggestions). - If you think there are no improvements to be made, don't return **that** object from the payload. - Rest, **return everything as it is (in the same order)** along with your suggestions. Ignore formatting issues. - IMPORTANT: - - Don't be lazy. - - If something is deleted (type: "del"), compare it with what's added (type: "add") in place of it. If it's completely different, ignore the deleted part and give suggestions based on the added (type: "add") part. - - If it's more appropriate to club the "add" parts together and then give suggestions, then do that. For example, if there are 3 "add" parts such as "function subtract(a, b) {", "return a - b;" and "}", then you can club them together and give suggestions. - - Only modify/add the "suggestions" property (if required). - - DO NOT modify the value of any other property. Return them as they are in the input. - - Make sure the suggestion positions are accurate as they are in the input and suggestions are related to the code changes on those positions (see "content" or "previously" (if it exists) property). - - If there is a suggestion which is similar across multiple positions, only suggest that change at any one of those positions. - - Keep the suggestions precise and to the point (in a constructive way). - - If possible, add references to some really good resources like stackoverflow or from programming articles, blogs, etc. for suggested code changes. Keep the references in context of the programming language you are reviewing. - - Suggestions should be inclusive of the rules (if any) provided by the user. - - Only make suggestions when they are significant, relevant and add value to the code changes. - - Don't make suggestions which are obvious for the user to know. For example, if a package is imported in the code, it's obvious that it should have been installed first. - - Give suggested code changes in markdown format if required, and use code blocks instead of inline code if needed. - - If there are no suggestions, please don't spam with "No suggestions". - - Rules are not exhaustive, so use you own judgement as well. - - Rules start with and are separated by -- -`; - -const FILES_IGNORED_BY_DEFAULT = [ - "**/node_modules/**", - "**/package-lock.json", - "**/yarn.lock", - ".cache/**", - "**/*.{jpg,jpeg,png,svg,webp,avif,gif,ico,woff,woff2,ttf,otf}", -]; - - +const DEFAULT_MODEL = { + OPENAI: { + name: "gpt-4o-2024-08-06", + }, + ANTHROPIC: { + name: "claude-3-7-sonnet-latest", + }, + MISTRAL: { + name: "pixtral-12b-2409", + }, + OPENROUTER: { + name: "deepseek/deepseek-r1", + }, + GOOGLE: { + name: "gemini-2.5-pro-preview-05-06", + }, +}; + +const BASE_URL = { + OPENROUTER: "https://openrouter.ai/api/v1", + GOOGLE: "https://generativelanguage.googleapis.com/v1beta/openai/", +}; + +const COMMON_SYSTEM_PROMPT = ` + You are a highly experienced software engineer and code reviewer with a focus on code quality, maintainability, and adherence to best practices. + Your goal is to provide thorough, constructive, and actionable feedback to help developers improve their code. + You consider various aspects, including readability, efficiency, and security. + The user will provide you with a diff payload of a pull request and some rules on how the code should be (they are separated by --), and you have to make suggestions on what can be improved by looking at the diff changes. You might be provided with a pull request description for more context (most probably in markdown format). + Take the user input diff payload and analyze the changes from the "content" property (ignore the first "+" or "-" character at the start of the string because that's just a diff character) of the payload and suggest some improvements (if an object contains "previously" property, compare it against the "content" property and consider that as well to make suggestions). + If you think there are no improvements to be made, don't return **that** object from the payload. + Rest, **return everything as it is (in the same order)** along with your suggestions. Ignore formatting issues. + IMPORTANT: + - Don't be lazy. + - If something is deleted (type: "del"), compare it with what's added (type: "add") in place of it. If it's completely different, ignore the deleted part and give suggestions based on the added (type: "add") part. + - If it's more appropriate to club the "add" parts together and then give suggestions, then do that. For example, if there are 3 "add" parts such as "function subtract(a, b) {", "return a - b;" and "}", then you can club them together and give suggestions. + - Only modify/add the "suggestions" property (if required). + - DO NOT modify the value of any other property. Return them as they are in the input. + - Make sure the suggestion positions are accurate as they are in the input and suggestions are related to the code changes on those positions (see "content" or "previously" (if it exists) property). + - If there is a suggestion which is similar across multiple positions, only suggest that change at any one of those positions. + - Keep the suggestions precise and to the point (in a constructive way). + - If possible, add references to some really good resources like stackoverflow or from programming articles, blogs, etc. for suggested code changes. Keep the references in context of the programming language you are reviewing. + - Suggestions should be inclusive of the rules (if any) provided by the user. + - Only make suggestions when they are significant, relevant and add value to the code changes. + - Don't make suggestions which are obvious for the user to know. For example, if a package is imported in the code, it's obvious that it should have been installed first. + - Give suggested code changes in markdown format if required, and use code blocks instead of inline code if needed. + - If there are no suggestions, please don't spam with "No suggestions". + - Rules are not exhaustive, so use you own judgement as well. + - Rules start with and are separated by -- +`; + +const FILES_IGNORED_BY_DEFAULT = [ + "**/node_modules/**", + "**/package-lock.json", + "**/yarn.lock", + ".cache/**", + "**/*.{jpg,jpeg,png,svg,webp,avif,gif,ico,woff,woff2,ttf,otf}", +]; + + ;// CONCATENATED MODULE: ./index.js - - - - - - - - - - - - - - - - -/** - * @typedef {import("@actions/github/lib/utils").GitHub} GitHub - * @typedef {z.infer[]} rawCommentsPayload - * @typedef {z.infer} suggestionsPayload - * @typedef {{ path: string, line: number, body: string }[]} CommentsPayload - * @typedef {InstanceType} OctokitApi - * @typedef {parseDiff.File[]} ParsedDiff - * @typedef {{ body: string | null }} PullRequestContext - * @typedef {'openai' | 'anthropic' | 'mistral' | 'openrouter' | 'google'} AIPlatform - * @typedef {OpenAI | Anthropic | ChatMistralAI} AIPlatformSDK - * @typedef {{ - * info: (message: string) => void, - * warning: (message: string) => void, - * error: (error: string) => void - * }} Logger - */ - -/** - * @param {string} name - * @param {AIPlatform} platform - * @returns {string} - */ -function getModelName(name, platform) { - return name !== "" ? name : DEFAULT_MODEL[`${platform.toUpperCase()}`].name; -} - -function extractComments() { - /** - * @param {ParsedDiff} parsedDiff - * @returns {rawCommentsPayload} - */ - const rawComments = parsedDiff => - parsedDiff.reduce((acc, file) => { - const filePath = file.deleted ? file.from : file.to; - let diffRelativePosition = 0; - return acc.concat( - file.chunks.reduce((accc, chunk, i) => { - if (i !== 0) { - diffRelativePosition++; - } - return accc.concat( - chunk.changes - .map(change => { - return { - ...change, - relativePosition: ++diffRelativePosition, - }; - }) - .filter( - change => - change.type !== "normal" && !change.content.includes("No newline at end of file") - ) - .map((change, i, arr) => { - if (change.content === "+" || change.content === "-") { - return null; - } - - if (change.type === "add") { - /** - * It checks if the current change (change) is an addition that immediately follows a deletion (arr[i - 1].type === 'del') on the same line (change.ln === arr[i - 1].ln). - */ - if (i > 0 && arr[i - 1].type === "del" && change.ln === arr[i - 1].ln) { - return { - path: filePath, - position: change.relativePosition, - line: change.ln, - change, - previously: arr[i - 1].content, - }; - } - - return { - path: filePath, - position: change.relativePosition, - line: change.ln, - change, - }; - } - - if ( - i < arr.length - 1 && - change.type === "del" && - change.ln === arr[i + 1].ln && - arr[i + 1].type === "add" - ) { - return null; - } - - return { - path: filePath, - position: change.relativePosition, - line: change.ln, - change, - }; - }) - .filter(i => i) /** filter out nulls */ - ); - }, []) - ); - }, []); - - /** - * @param {rawCommentsPayload} rawComments - * @param {string[]} filesToIgnore - * @returns {rawCommentsPayload} - */ - const filteredRawComments = (rawComments, filesToIgnore) => - rawComments.filter(comment => { - return !micromatch.isMatch(comment.path, filesToIgnore, { dot: true }); - }); - - /** - * @param {suggestionsPayload} suggestions - * @returns {CommentsPayload} - */ - const commentsWithSuggestions = suggestions => - suggestions.commentsToAdd - .filter(i => i["suggestions"]) - .map(i => { - return { - path: i.path, - // position: i.position, - line: i.line, - body: i.suggestions, - }; - }); - - return { - raw: rawComments, - filteredRaw: filteredRawComments, - comments: commentsWithSuggestions, - }; -} - -/** - * @param {string} rules - * @param {rawCommentsPayload} rawComments - * @param {PullRequestContext} pullRequestContext - * @returns {string} - */ -function getUserPrompt(rules, rawComments, pullRequestContext) { - return `I want you to code review a pull request ${rules ? ` by including the following rules: ${rules} \nThe rules provided describe how the code should be` : ""}. Here's the diff payload from the pull request: - ${JSON.stringify(rawComments)} - ${pullRequestContext.body ? `\nAlso, here's the pull request description on what it's trying to do to give you some more context (keep in mind that the description is not always accurate and can be incorrect, so compare the code changes in the diff to the description): ${pullRequestContext.body})` : ""}.`; -} - -/** - * @param {{ - * rawComments: rawCommentsPayload, - * openAI: OpenAI, - * rules: string, - * modelName: string, - * pullRequestContext: PullRequestContext, - * platform: AIPlatform - * }} params - * @returns {Promise} - */ -async function useOpenAI({ rawComments, openAI, rules, modelName, pullRequestContext, platform }) { - const modelDeepseek = /deepseek/i.test(getModelName(modelName, platform)); - const result = !modelDeepseek - ? await openAI.beta.chat.completions.parse({ - model: getModelName(modelName, platform), - messages: [ - { - role: "system", - content: COMMON_SYSTEM_PROMPT, - }, - { - role: "user", - content: getUserPrompt(rules, rawComments, pullRequestContext), - }, - ], - response_format: zodResponseFormat(diffPayloadSchema, "json_diff_response"), - }) - : await openAI.chat.completions.create({ - model: getModelName(modelName, platform), - messages: [ - { - role: "system", - content: COMMON_SYSTEM_PROMPT, - }, - { - role: "user", - content: `${getUserPrompt(rules, rawComments, pullRequestContext)} - IMP: give the output in a valid JSON string (it should be not be wrapped in markdown, just plain json object) and stick to the schema mentioned here: - { - commentsToAdd: { - path: string; - position: number; - line: number; - change: { - type: string; - add: boolean; - ln: number; - content: string; - relativePosition: number; - }; - previously?: string | undefined; - suggestions?: string | undefined; - }[]; - }.`, - }, - ], - response_format: { - type: "json_object", - }, - }); - - const { message } = result.choices[0]; - - if (message.refusal) { - throw new Error(`the model refused to generate suggestions - ${message.refusal}`); - } - - return modelDeepseek ? JSON.parse(message.content) : message.parsed; -} - -/** - * @param {{ - * rawComments: rawCommentsPayload, - * anthropic: Anthropic, - * rules: string, - * modelName: string, - * pullRequestContext: PullRequestContext - * }} params - * @returns {Promise} - */ -async function useAnthropic({ rawComments, anthropic, rules, modelName, pullRequestContext }) { - const { definitions } = zodToJsonSchema_zodToJsonSchema(diffPayloadSchema, "diffPayloadSchema"); - const result = await anthropic.messages.create({ - max_tokens: 8192, - model: getModelName(modelName, "anthropic"), - system: COMMON_SYSTEM_PROMPT, - tools: [ - { - name: "structuredOutput", - description: "Structured Output", - input_schema: definitions["diffPayloadSchema"], - }, - ], - tool_choice: { - type: "tool", - name: "structuredOutput", - }, - messages: [ - { - role: "user", - content: getUserPrompt(rules, rawComments, pullRequestContext), - }, - ], - }); - - let parsed = null; - for (const block of result.content) { - if (block.type === "tool_use") { - parsed = block.input; - break; - } - } - - return parsed; -} - -/** - * @param {{ - * rawComments: rawCommentsPayload, - * mistral: ChatMistralAI, - * rules: string, - * modelName: string, - * pullRequestContext: PullRequestContext - * }} params - * @returns {Promise} - */ -async function useMistral({ rawComments, mistral, rules, modelName, pullRequestContext }) { - mistral.model = getModelName(modelName, "mistral"); - mistral.safePrompt = true; - - const parser = StructuredOutputParser.fromZodSchema(diffPayloadSchemaWithRequiredSuggestions); - - const result = await mistral - .withStructuredOutput(diffPayloadSchemaWithRequiredSuggestions, { - name: "diffPayloadSchemaWithRequiredSuggestions", - method: "json_mode", - }) - .invoke([ - ["system", COMMON_SYSTEM_PROMPT], - [ - "user", - `${getUserPrompt(rules, rawComments, pullRequestContext)}\n${parser.getFormatInstructions()}\nDon't give partial response. Sometimes the json is cut off in between. Please provide the full json response.`, - ], - ]); - - if (!result || result.commentsToAdd.length === 0) { - throw new Error(`the model refused to generate suggestions - ${result}`); - } - - await parser.invoke(new ai_AIMessage(JSON.stringify(result))); // validate output with schema - return result; -} - -/** - * Retries an async function with exponential backoff - * @template T - * @param {() => Promise} fn The async function to retry - * @param {{ - * retries?: number, - * initialDelay?: number, - * maxDelay?: number, - * backoffFactor?: number, - * retryableErrors?: string[], - * onRetry?: (info: { - * error: Error, - * attempt: number, - * remainingAttempts: number, - * delay: number - * }) => void, - * }} options Configuration options - * @returns {Promise} - */ -async function retry( - fn, - { - retries = 3, - initialDelay = 1500, // Start with 1.5 seconds - backoffFactor = 2, // Double the delay each time - maxDelay = 10000, // Never wait more than 10 seconds - nonRetryableErrors = ["Unsupported AI platform", "Too many tokens"], - onRetry = null, - } = {} -) { - let lastError; - let delay = initialDelay; - - if (retries === 0) { - return await fn(); - } - - for (let attempt = 0; attempt < retries; attempt++) { - try { - return await fn(); - } catch (error) { - lastError = error; - - const shouldNotRetry = nonRetryableErrors.some(errMsg => - error.message.toLowerCase().includes(errMsg.toLowerCase()) - ); - - if (shouldNotRetry || attempt === retries - 1) { - throw error; - } - - if (onRetry) { - onRetry({ - error, - attempt: attempt + 1, - remainingAttempts: retries - attempt - 1, - delay, - }); - } - - await new Promise(resolve => setTimeout(resolve, delay)); - delay = Math.min(delay * backoffFactor, maxDelay); - } - } - - throw lastError; -} - -/** - * @param {{ - * platform: AIPlatform, - * rawComments: rawCommentsPayload, - * platformSDK: AIPlatformSDK, - * rules: string, - * modelName: string, - * pullRequestContext: PullRequestContext, - * maxRetries: number - * }} params - * @returns {Promise} - */ -async function getSuggestions({ - platform, - rawComments, - platformSDK, - rules, - modelName, - pullRequestContext, - maxRetries, -}) { - const { error, warning } = log({ withTimestamp: true }); // eslint-disable-line no-use-before-define - - try { - return await retry( - async () => { - if (platform === "openai" || platform === "google" || platform === "openrouter") { - return await useOpenAI({ - rawComments, - openAI: platformSDK, - rules, - modelName, - pullRequestContext, - platform, - }); - } - - if (platform === "anthropic") { - return await useAnthropic({ - rawComments, - anthropic: platformSDK, - rules, - modelName, - pullRequestContext, - }); - } - - if (platform === "mistral") { - return await useMistral({ - rawComments, - mistral: platformSDK, - rules, - modelName, - pullRequestContext, - }); - } - - throw new Error(`Unsupported AI platform: ${platform}`); - }, - { - retries: maxRetries ?? 3, - onRetry: ({ error: retryError, attempt, remainingAttempts, delay }) => { - error(`Attempt ${attempt} failed: ${retryError.message}.`); - warning(`Retrying in ${delay}ms. Remaining attempts: ${remainingAttempts}.`); - }, - } - ); - } catch (err) { - error(`Could not generate suggestions: ${err.message}`); - core.setFailed(`Could not generate suggestions: ${err.message}`); - return null; - } -} - -/** - * @param {rawCommentsPayload} rawComments - * @param {CommentsPayload} comments - * @returns {CommentsPayload} - */ -function filterPositionsNotPresentInRawPayload(rawComments, comments) { - return comments.filter(comment => - rawComments.some(rawComment => rawComment.path === comment.path && rawComment.line === comment.line) - ); -} - -/** - * @param {suggestionsPayload} suggestions - * @param {OctokitApi} octokit - * @param {rawCommentsPayload} rawComments - * @param {string} modelName - */ -async function addReviewComments(suggestions, octokit, rawComments, modelName) { - const { info } = log({ withTimestamp: true }); // eslint-disable-line no-use-before-define - const comments = filterPositionsNotPresentInRawPayload(rawComments, extractComments().comments(suggestions)); - - try { - await octokit.rest.pulls.createReview({ - owner: github.context.repo.owner, - repo: github.context.repo.repo, - pull_number: github.context.payload.pull_request.number, - body: `Code Review by ${modelName}`, - event: "COMMENT", - comments, - }); - } catch (error) { - info(`Failed to add review comments: ${JSON.stringify(comments, null, 2)}`); - throw error; - } -} - -/** - * @param {OctokitApi} octokit - * @param {{ mode: 'diff' | 'json' }} options - */ -async function getPullRequestDetails(octokit, { mode }) { - let AcceptFormat = "application/vnd.github.raw+json"; - - if (mode === "diff") AcceptFormat = "application/vnd.github.diff"; - if (mode === "json") AcceptFormat = "application/vnd.github.raw+json"; - - return await octokit.rest.pulls.get({ - owner: github.context.repo.owner, - repo: github.context.repo.repo, - pull_number: github.context.payload.pull_request.number, - headers: { - accept: AcceptFormat, - }, - }); -} - -/** - * @param {OctokitApi} octokit - */ -async function getAllReviewsForPullRequest(octokit) { - return await octokit.rest.pulls.listReviews({ - owner: github.context.repo.owner, - repo: github.context.repo.repo, - pull_number: github.context.payload.pull_request.number, - }); -} - -/** - * @param {OctokitApi} octokit - * @param {number} review_id - */ -async function getAllCommentsUnderAReview(octokit, review_id) { - return await octokit.rest.pulls.listCommentsForReview({ - owner: github.context.repo.owner, - repo: github.context.repo.repo, - pull_number: github.context.payload.pull_request.number, - review_id, - }); -} - -/** - * @param {OctokitApi} octokit - * @param {number} comment_id - */ -async function deleteComment(octokit, comment_id) { - await octokit.rest.pulls.deleteReviewComment({ - owner: github.context.repo.owner, - repo: github.context.repo.repo, - comment_id, - }); -} - -/** - * @param {string} value - * @returns {boolean} - */ -function getBooleanValue(value) { - if (!value || value === "") return false; - return value.toLowerCase() === "true"; -} - -/** - * @param {{ withTimestamp: boolean }} options - * @returns {Logger} - */ -function log({ withTimestamp = true }) { - /** - * @param {string} str - * @returns {string} - */ - const getLogText = str => (withTimestamp ? `[${new Date().toISOString()}]: ${str}` : str); - return { - info: message => core.info(getLogText(message)), - warning: message => core.warning(getLogText(message)), - error: error => core.error(getLogText(error)), - }; -} - -/** - * Returns an instance of the AI platform SDK given the platform name and API key. - * - * @param {AIPlatform} platform - The name of the AI platform. - * @param {string} apiKey - The API key for the AI platform. - * @returns {AIPlatformSDK | Error} The AI platform SDK instance. - */ -function getPlatformSDK(platform, apiKey) { - if (platform === "openai") return new openai({ apiKey }); - if (platform === "anthropic") return new Anthropic({ apiKey }); - if (platform === "mistral") return new ChatMistralAI({ apiKey }); - if (platform === "openrouter") return new openai({ apiKey, baseURL: BASE_URL.OPENROUTER }); - if (platform === "google") return new openai({ apiKey, baseURL: BASE_URL.GOOGLE }); - - throw new Error(`Unsupported AI platform: ${platform}`); -} - -async function run() { - const { info, warning, error } = log({ withTimestamp: true }); - - try { - info("Retrieving tokens and inputs..."); - - const deleteExistingReviews = core.getInput("delete-existing-review-by-bot"); - const rules = core.getInput("rules"); - const token = core.getInput("repo-token"); - const modelName = core.getInput("ai-model-name"); - const modelToken = core.getInput("ai-model-api-key"); - const platform = core.getInput("platform"); - const filesToIgnore = core.getInput("filesToIgnore"); - const maxRetries = core.getInput("max-retries"); - const octokit = github.getOctokit(token); - - info("Initializing AI model..."); - const platformSDK = getPlatformSDK(platform, modelToken); - - if (github.context.payload.pull_request) { - info("Fetching pull request details..."); - const pullRequestDiff = await getPullRequestDetails(octokit, { - mode: "diff", - }); - const pullRequestData = await getPullRequestDetails(octokit, { - mode: "json", - }); - - if (getBooleanValue(deleteExistingReviews)) { - info("Preparing to delete existing comments..."); - - info("Fetching pull request reviews..."); - const reviews = await getAllReviewsForPullRequest(octokit); - - info(`Fetching reviews by bot...`); - const reviewsByBot = reviews.data.filter( - r => r.user.login === "github-actions[bot]" || r.user.type === "Bot" - ); // not possible to change the bot name - https://github.com/orgs/community/discussions/25853 - - if (reviewsByBot.length > 0) { - info(`Found ${reviewsByBot.length} reviews by bot...`); - warning("Deleting existing comments for all reviews by bot..."); - - for (const review of reviewsByBot) { - const reviewComments = await getAllCommentsUnderAReview(octokit, review.id); - - for (const comment of reviewComments.data) { - await deleteComment(octokit, comment.id); - await new Promise(resolve => setTimeout(resolve, 1500)); // Wait 1.5 seconds before deleting next comment to avoid rate limiting - } - } - } else { - info("No reviews by bot found. Skipping deleting existing comments for all reviews by bot..."); - } - } else { - info("Skipping deleting existing comments for all reviews by bot..."); - } - - info(`Reviewing pull request ${pullRequestDiff.url}...`); - const parsedDiff = parse_diff(pullRequestDiff.data); - const rawComments = extractComments().raw(parsedDiff); - - info("Getting files to ignore..."); - const filesToIgnoreList = [ - ...new Set( - filesToIgnore - .split(";") - .map(file => file.trim()) - .filter(file => file !== "") - .concat(FILES_IGNORED_BY_DEFAULT) - ), - ]; - - const filteredRawComments = extractComments().filteredRaw(rawComments, filesToIgnoreList); - - info(`Generating suggestions using model ${getModelName(modelName, platform)}...`); - const suggestions = await getSuggestions({ - platform, - rawComments: filteredRawComments, - platformSDK, - rules, - modelName, - maxRetries: Number(maxRetries), - pullRequestContext: { - body: pullRequestData.data.body, - }, - }); - - if (!suggestions) { - warning("Could not generate suggestions. Refer to the error log for more information and try again."); - return; - } - - if (suggestions.commentsToAdd.length === 0) { - info("No suggestions found. Code review complete. All good!"); - return; - } - - info("Adding review comments..."); - await addReviewComments(suggestions, octokit, filteredRawComments, getModelName(modelName, platform)); - - info("Code review complete!"); - } else { - warning("Not a pull request, skipping..."); - } - } catch (err) { - error(err); - core.setFailed(err.message); - } -} - -run(); + + + + + + + + + + + + + + + + +/** + * @typedef {import("@actions/github/lib/utils").GitHub} GitHub + * @typedef {z.infer[]} rawCommentsPayload + * @typedef {z.infer} suggestionsPayload + * @typedef {{ path: string, line: number, body: string }[]} CommentsPayload + * @typedef {InstanceType} OctokitApi + * @typedef {parseDiff.File[]} ParsedDiff + * @typedef {{ body: string | null }} PullRequestContext + * @typedef {'openai' | 'anthropic' | 'mistral' | 'openrouter' | 'google'} AIPlatform + * @typedef {OpenAI | Anthropic | ChatMistralAI} AIPlatformSDK + * @typedef {{ + * info: (message: string) => void, + * warning: (message: string) => void, + * error: (error: string) => void + * }} Logger + */ + +/** + * @param {string} name + * @param {AIPlatform} platform + * @returns {string} + */ +function getModelName(name, platform) { + return name !== "" ? name : DEFAULT_MODEL[`${platform.toUpperCase()}`].name; +} + +function extractComments() { + /** + * @param {ParsedDiff} parsedDiff + * @returns {rawCommentsPayload} + */ + const rawComments = parsedDiff => + parsedDiff.reduce((acc, file) => { + const filePath = file.deleted ? file.from : file.to; + let diffRelativePosition = 0; + return acc.concat( + file.chunks.reduce((accc, chunk, i) => { + if (i !== 0) { + diffRelativePosition++; + } + return accc.concat( + chunk.changes + .map(change => { + return { + ...change, + relativePosition: ++diffRelativePosition, + }; + }) + .filter( + change => + change.type !== "normal" && !change.content.includes("No newline at end of file") + ) + .map((change, i, arr) => { + if (change.content === "+" || change.content === "-") { + return null; + } + + if (change.type === "add") { + /** + * It checks if the current change (change) is an addition that immediately follows a deletion (arr[i - 1].type === 'del') on the same line (change.ln === arr[i - 1].ln). + */ + if (i > 0 && arr[i - 1].type === "del" && change.ln === arr[i - 1].ln) { + return { + path: filePath, + position: change.relativePosition, + line: change.ln, + change, + previously: arr[i - 1].content, + }; + } + + return { + path: filePath, + position: change.relativePosition, + line: change.ln, + change, + }; + } + + if ( + i < arr.length - 1 && + change.type === "del" && + change.ln === arr[i + 1].ln && + arr[i + 1].type === "add" + ) { + return null; + } + + return { + path: filePath, + position: change.relativePosition, + line: change.ln, + change, + }; + }) + .filter(i => i) /** filter out nulls */ + ); + }, []) + ); + }, []); + + /** + * @param {rawCommentsPayload} rawComments + * @param {string[]} filesToIgnore + * @returns {rawCommentsPayload} + */ + const filteredRawComments = (rawComments, filesToIgnore) => + rawComments.filter(comment => { + return !micromatch.isMatch(comment.path, filesToIgnore, { dot: true }); + }); + + /** + * @param {suggestionsPayload} suggestions + * @returns {CommentsPayload} + */ + const commentsWithSuggestions = suggestions => + suggestions.commentsToAdd + .filter(i => i["suggestions"]) + .map(i => { + return { + path: i.path, + // position: i.position, + line: i.line, + body: i.suggestions, + }; + }); + + return { + raw: rawComments, + filteredRaw: filteredRawComments, + comments: commentsWithSuggestions, + }; +} + +/** + * @param {string} rules + * @param {rawCommentsPayload} rawComments + * @param {PullRequestContext} pullRequestContext + * @returns {string} + */ +function getUserPrompt(rules, rawComments, pullRequestContext) { + return `I want you to code review a pull request ${rules ? ` by including the following rules: ${rules} \nThe rules provided describe how the code should be` : ""}. Here's the diff payload from the pull request: + ${JSON.stringify(rawComments)} + ${pullRequestContext.body ? `\nAlso, here's the pull request description on what it's trying to do to give you some more context (keep in mind that the description is not always accurate and can be incorrect, so compare the code changes in the diff to the description): ${pullRequestContext.body})` : ""}.`; +} + +/** + * @param {{ + * rawComments: rawCommentsPayload, + * openAI: OpenAI, + * rules: string, + * modelName: string, + * pullRequestContext: PullRequestContext, + * platform: AIPlatform + * }} params + * @returns {Promise} + */ +async function useOpenAI({ rawComments, openAI, rules, modelName, pullRequestContext, platform }) { + const modelDeepseek = /deepseek/i.test(getModelName(modelName, platform)); + const result = !modelDeepseek + ? await openAI.beta.chat.completions.parse({ + model: getModelName(modelName, platform), + messages: [ + { + role: "system", + content: COMMON_SYSTEM_PROMPT, + }, + { + role: "user", + content: getUserPrompt(rules, rawComments, pullRequestContext), + }, + ], + response_format: zodResponseFormat(diffPayloadSchema, "json_diff_response"), + }) + : await openAI.chat.completions.create({ + model: getModelName(modelName, platform), + messages: [ + { + role: "system", + content: COMMON_SYSTEM_PROMPT, + }, + { + role: "user", + content: `${getUserPrompt(rules, rawComments, pullRequestContext)} - IMP: give the output in a valid JSON string (it should be not be wrapped in markdown, just plain json object) and stick to the schema mentioned here: + { + commentsToAdd: { + path: string; + position: number; + line: number; + change: { + type: string; + add: boolean; + ln: number; + content: string; + relativePosition: number; + }; + previously?: string | undefined; + suggestions?: string | undefined; + }[]; + }.`, + }, + ], + response_format: { + type: "json_object", + }, + }); + + const { message } = result.choices[0]; + + if (message.refusal) { + throw new Error(`the model refused to generate suggestions - ${message.refusal}`); + } + + return modelDeepseek ? JSON.parse(message.content) : message.parsed; +} + +/** + * @param {{ + * rawComments: rawCommentsPayload, + * anthropic: Anthropic, + * rules: string, + * modelName: string, + * pullRequestContext: PullRequestContext + * }} params + * @returns {Promise} + */ +async function useAnthropic({ rawComments, anthropic, rules, modelName, pullRequestContext }) { + const { definitions } = zodToJsonSchema_zodToJsonSchema(diffPayloadSchema, "diffPayloadSchema"); + const result = await anthropic.messages.create({ + max_tokens: 8192, + model: getModelName(modelName, "anthropic"), + system: COMMON_SYSTEM_PROMPT, + tools: [ + { + name: "structuredOutput", + description: "Structured Output", + input_schema: definitions["diffPayloadSchema"], + }, + ], + tool_choice: { + type: "tool", + name: "structuredOutput", + }, + messages: [ + { + role: "user", + content: getUserPrompt(rules, rawComments, pullRequestContext), + }, + ], + }); + + let parsed = null; + for (const block of result.content) { + if (block.type === "tool_use") { + parsed = block.input; + break; + } + } + + return parsed; +} + +/** + * @param {{ + * rawComments: rawCommentsPayload, + * mistral: ChatMistralAI, + * rules: string, + * modelName: string, + * pullRequestContext: PullRequestContext + * }} params + * @returns {Promise} + */ +async function useMistral({ rawComments, mistral, rules, modelName, pullRequestContext }) { + mistral.model = getModelName(modelName, "mistral"); + mistral.safePrompt = true; + + const parser = StructuredOutputParser.fromZodSchema(diffPayloadSchemaWithRequiredSuggestions); + + const result = await mistral + .withStructuredOutput(diffPayloadSchemaWithRequiredSuggestions, { + name: "diffPayloadSchemaWithRequiredSuggestions", + method: "json_mode", + }) + .invoke([ + ["system", COMMON_SYSTEM_PROMPT], + [ + "user", + `${getUserPrompt(rules, rawComments, pullRequestContext)}\n${parser.getFormatInstructions()}\nDon't give partial response. Sometimes the json is cut off in between. Please provide the full json response.`, + ], + ]); + + if (!result || result.commentsToAdd.length === 0) { + throw new Error(`the model refused to generate suggestions - ${result}`); + } + + await parser.invoke(new ai_AIMessage(JSON.stringify(result))); // validate output with schema + return result; +} + +/** + * Retries an async function with exponential backoff + * @template T + * @param {() => Promise} fn The async function to retry + * @param {{ + * retries?: number, + * initialDelay?: number, + * maxDelay?: number, + * backoffFactor?: number, + * retryableErrors?: string[], + * onRetry?: (info: { + * error: Error, + * attempt: number, + * remainingAttempts: number, + * delay: number + * }) => void, + * }} options Configuration options + * @returns {Promise} + */ +async function retry( + fn, + { + retries = 3, + initialDelay = 1500, // Start with 1.5 seconds + backoffFactor = 2, // Double the delay each time + maxDelay = 10000, // Never wait more than 10 seconds + nonRetryableErrors = ["Unsupported AI platform", "Too many tokens"], + onRetry = null, + } = {} +) { + let lastError; + let delay = initialDelay; + + if (retries === 0) { + return await fn(); + } + + for (let attempt = 0; attempt < retries; attempt++) { + try { + return await fn(); + } catch (error) { + lastError = error; + + if (onRetry) { + onRetry({ + error, + attempt: attempt + 1, + remainingAttempts: retries - attempt - 1, + delay, + }); + } + + const shouldNotRetry = nonRetryableErrors.some(errMsg => + error.message.toLowerCase().includes(errMsg.toLowerCase()) + ); + + if (shouldNotRetry || attempt === retries - 1) { + throw error; + } + + await new Promise(resolve => setTimeout(resolve, delay)); + delay = Math.min(delay * backoffFactor, maxDelay); + } + } + + throw lastError; +} + +/** + * @param {{ + * platform: AIPlatform, + * rawComments: rawCommentsPayload, + * platformSDK: AIPlatformSDK, + * rules: string, + * modelName: string, + * pullRequestContext: PullRequestContext, + * maxRetries: number + * }} params + * @returns {Promise} + */ +async function getSuggestions({ + platform, + rawComments, + platformSDK, + rules, + modelName, + pullRequestContext, + maxRetries, +}) { + const { error, warning } = log({ withTimestamp: true }); // eslint-disable-line no-use-before-define + + try { + return await retry( + async () => { + if (platform === "openai" || platform === "google" || platform === "openrouter") { + return await useOpenAI({ + rawComments, + openAI: platformSDK, + rules, + modelName, + pullRequestContext, + platform, + }); + } + + if (platform === "anthropic") { + return await useAnthropic({ + rawComments, + anthropic: platformSDK, + rules, + modelName, + pullRequestContext, + }); + } + + if (platform === "mistral") { + return await useMistral({ + rawComments, + mistral: platformSDK, + rules, + modelName, + pullRequestContext, + }); + } + + throw new Error(`Unsupported AI platform: ${platform}`); + }, + { + retries: maxRetries ?? 3, + onRetry: ({ error: retryError, attempt, remainingAttempts, delay }) => { + error(`Attempt ${attempt} failed: ${retryError.message}.`); + + if (remainingAttempts !== 0) { + warning(`Retrying in ${delay}ms. Remaining attempts: ${remainingAttempts}.`); + } + }, + } + ); + } catch (err) { + error(`Could not generate suggestions: ${err.message}`); + core.setFailed(`Could not generate suggestions: ${err.message}`); + return null; + } +} + +/** + * @param {rawCommentsPayload} rawComments + * @param {CommentsPayload} comments + * @returns {CommentsPayload} + */ +function filterPositionsNotPresentInRawPayload(rawComments, comments) { + return comments.filter(comment => + rawComments.some(rawComment => rawComment.path === comment.path && rawComment.line === comment.line) + ); +} + +/** + * @param {suggestionsPayload} suggestions + * @param {OctokitApi} octokit + * @param {rawCommentsPayload} rawComments + * @param {string} modelName + */ +async function addReviewComments(suggestions, octokit, rawComments, modelName) { + const { info } = log({ withTimestamp: true }); // eslint-disable-line no-use-before-define + const comments = filterPositionsNotPresentInRawPayload(rawComments, extractComments().comments(suggestions)); + + try { + await octokit.rest.pulls.createReview({ + owner: github.context.repo.owner, + repo: github.context.repo.repo, + pull_number: github.context.payload.pull_request.number, + body: `Code Review by ${modelName}`, + event: "COMMENT", + comments, + }); + } catch (error) { + info(`Failed to add review comments: ${JSON.stringify(comments, null, 2)}`); + throw error; + } +} + +/** + * @param {OctokitApi} octokit + * @param {{ mode: 'diff' | 'json' }} options + */ +async function getPullRequestDetails(octokit, { mode }) { + let AcceptFormat = "application/vnd.github.raw+json"; + + if (mode === "diff") AcceptFormat = "application/vnd.github.diff"; + if (mode === "json") AcceptFormat = "application/vnd.github.raw+json"; + + return await octokit.rest.pulls.get({ + owner: github.context.repo.owner, + repo: github.context.repo.repo, + pull_number: github.context.payload.pull_request.number, + headers: { + accept: AcceptFormat, + }, + }); +} + +/** + * @param {OctokitApi} octokit + */ +async function getAllReviewsForPullRequest(octokit) { + return await octokit.rest.pulls.listReviews({ + owner: github.context.repo.owner, + repo: github.context.repo.repo, + pull_number: github.context.payload.pull_request.number, + }); +} + +/** + * @param {OctokitApi} octokit + * @param {number} review_id + */ +async function getAllCommentsUnderAReview(octokit, review_id) { + return await octokit.rest.pulls.listCommentsForReview({ + owner: github.context.repo.owner, + repo: github.context.repo.repo, + pull_number: github.context.payload.pull_request.number, + review_id, + }); +} + +/** + * @param {OctokitApi} octokit + * @param {number} comment_id + */ +async function deleteComment(octokit, comment_id) { + await octokit.rest.pulls.deleteReviewComment({ + owner: github.context.repo.owner, + repo: github.context.repo.repo, + comment_id, + }); +} + +/** + * @param {string} value + * @returns {boolean} + */ +function getBooleanValue(value) { + if (!value || value === "") return false; + return value.toLowerCase() === "true"; +} + +/** + * @param {{ withTimestamp: boolean }} options + * @returns {Logger} + */ +function log({ withTimestamp = true }) { + /** + * @param {string} str + * @returns {string} + */ + const getLogText = str => (withTimestamp ? `[${new Date().toISOString()}]: ${str}` : str); + return { + info: message => core.info(getLogText(message)), + warning: message => core.warning(getLogText(message)), + error: error => core.error(getLogText(error)), + }; +} + +/** + * Returns an instance of the AI platform SDK given the platform name and API key. + * + * @param {AIPlatform} platform - The name of the AI platform. + * @param {string} apiKey - The API key for the AI platform. + * @returns {AIPlatformSDK | Error} The AI platform SDK instance. + */ +function getPlatformSDK(platform, apiKey) { + if (platform === "openai") return new openai({ apiKey }); + if (platform === "anthropic") return new Anthropic({ apiKey }); + if (platform === "mistral") return new ChatMistralAI({ apiKey }); + if (platform === "openrouter") return new openai({ apiKey, baseURL: BASE_URL.OPENROUTER }); + if (platform === "google") return new openai({ apiKey, baseURL: BASE_URL.GOOGLE }); + + throw new Error(`Unsupported AI platform: ${platform}`); +} + +async function run() { + const { info, warning, error } = log({ withTimestamp: true }); + + try { + info("Retrieving tokens and inputs..."); + + const deleteExistingReviews = core.getInput("delete-existing-review-by-bot"); + const rules = core.getInput("rules"); + const token = core.getInput("repo-token"); + const modelName = core.getInput("ai-model-name"); + const modelToken = core.getInput("ai-model-api-key"); + const platform = core.getInput("platform"); + const filesToIgnore = core.getInput("filesToIgnore"); + const maxRetries = core.getInput("max-retries"); + const octokit = github.getOctokit(token); + + info("Initializing AI model..."); + const platformSDK = getPlatformSDK(platform, modelToken); + + if (github.context.payload.pull_request) { + info("Fetching pull request details..."); + const pullRequestDiff = await getPullRequestDetails(octokit, { + mode: "diff", + }); + const pullRequestData = await getPullRequestDetails(octokit, { + mode: "json", + }); + + if (getBooleanValue(deleteExistingReviews)) { + info("Preparing to delete existing comments..."); + + info("Fetching pull request reviews..."); + const reviews = await getAllReviewsForPullRequest(octokit); + + info(`Fetching reviews by bot...`); + const reviewsByBot = reviews.data.filter( + r => r.user.login === "github-actions[bot]" || r.user.type === "Bot" + ); // not possible to change the bot name - https://github.com/orgs/community/discussions/25853 + + if (reviewsByBot.length > 0) { + info(`Found ${reviewsByBot.length} reviews by bot...`); + warning("Deleting existing comments for all reviews by bot..."); + + for (const review of reviewsByBot) { + const reviewComments = await getAllCommentsUnderAReview(octokit, review.id); + + for (const comment of reviewComments.data) { + await deleteComment(octokit, comment.id); + await new Promise(resolve => setTimeout(resolve, 1500)); // Wait 1.5 seconds before deleting next comment to avoid rate limiting + } + } + } else { + info("No reviews by bot found. Skipping deleting existing comments for all reviews by bot..."); + } + } else { + info("Skipping deleting existing comments for all reviews by bot..."); + } + + info(`Reviewing pull request ${pullRequestDiff.url}...`); + const parsedDiff = parse_diff(pullRequestDiff.data); + const rawComments = extractComments().raw(parsedDiff); + + info("Getting files to ignore..."); + const filesToIgnoreList = [ + ...new Set( + filesToIgnore + .split(";") + .map(file => file.trim()) + .filter(file => file !== "") + .concat(FILES_IGNORED_BY_DEFAULT) + ), + ]; + + const filteredRawComments = extractComments().filteredRaw(rawComments, filesToIgnoreList); + + info(`Generating suggestions using model ${getModelName(modelName, platform)}...`); + const suggestions = await getSuggestions({ + platform, + rawComments: filteredRawComments, + platformSDK, + rules, + modelName, + maxRetries: maxRetries === "" ? null : Number(maxRetries), + pullRequestContext: { + body: pullRequestData.data.body, + }, + }); + + if (!suggestions) { + warning("Could not generate suggestions. Refer to the error log for more information and try again."); + return; + } + + if (suggestions.commentsToAdd.length === 0) { + info("No suggestions found. Code review complete. All good!"); + return; + } + + info("Adding review comments..."); + await addReviewComments(suggestions, octokit, filteredRawComments, getModelName(modelName, platform)); + + info("Code review complete!"); + } else { + warning("Not a pull request, skipping..."); + } + } catch (err) { + error(err); + core.setFailed(err.message); + } +} + +run(); diff --git a/index.js b/index.js index 3af80a1..92fa36e 100644 --- a/index.js +++ b/index.js @@ -356,14 +356,6 @@ async function retry( } catch (error) { lastError = error; - const shouldNotRetry = nonRetryableErrors.some(errMsg => - error.message.toLowerCase().includes(errMsg.toLowerCase()) - ); - - if (shouldNotRetry || attempt === retries - 1) { - throw error; - } - if (onRetry) { onRetry({ error, @@ -373,6 +365,14 @@ async function retry( }); } + const shouldNotRetry = nonRetryableErrors.some(errMsg => + error.message.toLowerCase().includes(errMsg.toLowerCase()) + ); + + if (shouldNotRetry || attempt === retries - 1) { + throw error; + } + await new Promise(resolve => setTimeout(resolve, delay)); delay = Math.min(delay * backoffFactor, maxDelay); } @@ -444,7 +444,10 @@ async function getSuggestions({ retries: maxRetries ?? 3, onRetry: ({ error: retryError, attempt, remainingAttempts, delay }) => { error(`Attempt ${attempt} failed: ${retryError.message}.`); - warning(`Retrying in ${delay}ms. Remaining attempts: ${remainingAttempts}.`); + + if (remainingAttempts !== 0) { + warning(`Retrying in ${delay}ms. Remaining attempts: ${remainingAttempts}.`); + } }, } ); @@ -672,7 +675,7 @@ async function run() { platformSDK, rules, modelName, - maxRetries: Number(maxRetries), + maxRetries: maxRetries === "" ? null : Number(maxRetries), pullRequestContext: { body: pullRequestData.data.body, }, From a2c0ea82745d31e0fee4ed7090fe02d568eee174 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 20:33:04 +0530 Subject: [PATCH 02/14] chore: upgrade default gemini model as previous model will be deprecated soon --- dist/index.js | 2 +- utils/constants.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/index.js b/dist/index.js index f633a6e..1cda1a5 100644 --- a/dist/index.js +++ b/dist/index.js @@ -111443,7 +111443,7 @@ const DEFAULT_MODEL = { name: "deepseek/deepseek-r1", }, GOOGLE: { - name: "gemini-2.5-pro-preview-05-06", + name: "gemini-2.5-pro-preview-06-05", }, }; diff --git a/utils/constants.js b/utils/constants.js index 9b777c7..26d7a53 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -12,7 +12,7 @@ const DEFAULT_MODEL = { name: "deepseek/deepseek-r1", }, GOOGLE: { - name: "gemini-2.5-pro-preview-05-06", + name: "gemini-2.5-pro-preview-06-05", }, }; From 1c97f891d05d164c90eea98120b2fce8432b6885 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 20:51:55 +0530 Subject: [PATCH 03/14] chore (docs): update --- README.md | 4 ++-- dist/index.js | 2 +- utils/constants.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index eb10d7d..99e56a6 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ They can be accessed in the workflow file using `${{ secrets.YOUR_KEY_NAME }}`. ### 4. `ai-model-name` (Optional) -Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-4o-2024-08-06` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-05-06` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `deepseek/deepseek-r1` for OpenRouter if not specified. Here's a list of supported models: +Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-4o-2024-08-06` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-05-06` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `google/gemini-2.5-pro-preview-06-05` for OpenRouter if not specified. Here's a list of supported models: For OpenAI: @@ -141,7 +141,7 @@ For Mistral: For OpenRouter: -- [deepseek/deepseek-r1](https://openrouter.ai/deepseek/deepseek-r1). +- Any of the models listed [here in OpenRouter](https://openrouter.ai/models?fmt=table&supported_parameters=response_format) that support `structured outputs`/`response_format`. For Google: diff --git a/dist/index.js b/dist/index.js index 1cda1a5..7ec12d9 100644 --- a/dist/index.js +++ b/dist/index.js @@ -111440,7 +111440,7 @@ const DEFAULT_MODEL = { name: "pixtral-12b-2409", }, OPENROUTER: { - name: "deepseek/deepseek-r1", + name: "google/gemini-2.5-pro-preview-06-05", }, GOOGLE: { name: "gemini-2.5-pro-preview-06-05", diff --git a/utils/constants.js b/utils/constants.js index 26d7a53..7a3c417 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -9,7 +9,7 @@ const DEFAULT_MODEL = { name: "pixtral-12b-2409", }, OPENROUTER: { - name: "deepseek/deepseek-r1", + name: "google/gemini-2.5-pro-preview-06-05", }, GOOGLE: { name: "gemini-2.5-pro-preview-06-05", From fecb90200c9928e8285770954e8f707ec7edf8a3 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 20:56:23 +0530 Subject: [PATCH 04/14] 3.3.0 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index d9c6fd0..058ffe4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "better", - "version": "3.2.1", + "version": "3.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "better", - "version": "3.2.1", + "version": "3.3.0", "license": "ISC", "dependencies": { "@actions/core": "^1.11.1", diff --git a/package.json b/package.json index 3400c3a..6960ce1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "better", - "version": "3.2.1", + "version": "3.3.0", "main": "index.js", "type": "module", "scripts": { From 0f38a28b9425b2919bd3dd8de933fce1e4c807ef Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 21:01:32 +0530 Subject: [PATCH 05/14] chore: update default openai model from 4o to 4.1 --- README.md | 2 +- dist/index.js | 2 +- utils/constants.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 99e56a6..36f7ef6 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ They can be accessed in the workflow file using `${{ secrets.YOUR_KEY_NAME }}`. ### 4. `ai-model-name` (Optional) -Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-4o-2024-08-06` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-05-06` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `google/gemini-2.5-pro-preview-06-05` for OpenRouter if not specified. Here's a list of supported models: +Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-4.1-2025-04-14` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-06-05` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `google/gemini-2.5-pro-preview-06-05` for OpenRouter if not specified. Here's a list of supported models: For OpenAI: diff --git a/dist/index.js b/dist/index.js index 7ec12d9..81f94ab 100644 --- a/dist/index.js +++ b/dist/index.js @@ -111431,7 +111431,7 @@ const diffPayloadSchemaWithRequiredSuggestions = diffPayloadSchema.extend({ ;// CONCATENATED MODULE: ./utils/constants.js const DEFAULT_MODEL = { OPENAI: { - name: "gpt-4o-2024-08-06", + name: "gpt-4.1-2025-04-14", }, ANTHROPIC: { name: "claude-3-7-sonnet-latest", diff --git a/utils/constants.js b/utils/constants.js index 7a3c417..61d1499 100644 --- a/utils/constants.js +++ b/utils/constants.js @@ -1,6 +1,6 @@ const DEFAULT_MODEL = { OPENAI: { - name: "gpt-4o-2024-08-06", + name: "gpt-4.1-2025-04-14", }, ANTHROPIC: { name: "claude-3-7-sonnet-latest", From b74f685a5fc8153f49b05833fcc2377a0f5d09b9 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 21:05:57 +0530 Subject: [PATCH 06/14] fix: increase review and comment fetch list to more than 30 (per_page default) --- dist/index.js | 2 ++ index.js | 2 ++ 2 files changed, 4 insertions(+) diff --git a/dist/index.js b/dist/index.js index 81f94ab..6197683 100644 --- a/dist/index.js +++ b/dist/index.js @@ -112014,6 +112014,7 @@ async function getAllReviewsForPullRequest(octokit) { owner: github.context.repo.owner, repo: github.context.repo.repo, pull_number: github.context.payload.pull_request.number, + per_page: 500, }); } @@ -112027,6 +112028,7 @@ async function getAllCommentsUnderAReview(octokit, review_id) { repo: github.context.repo.repo, pull_number: github.context.payload.pull_request.number, review_id, + per_page: 500, }); } diff --git a/index.js b/index.js index 92fa36e..1ed9b86 100644 --- a/index.js +++ b/index.js @@ -522,6 +522,7 @@ async function getAllReviewsForPullRequest(octokit) { owner: github.context.repo.owner, repo: github.context.repo.repo, pull_number: github.context.payload.pull_request.number, + per_page: 500, }); } @@ -535,6 +536,7 @@ async function getAllCommentsUnderAReview(octokit, review_id) { repo: github.context.repo.repo, pull_number: github.context.payload.pull_request.number, review_id, + per_page: 500, }); } From 3d746fb63b4e331146802b7a18a8ff0f5a5f2277 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 21:20:52 +0530 Subject: [PATCH 07/14] chore: upgrade deps except openai --- dist/index.js | 60188 ++++++++++++++++++++++++++------------------ package-lock.json | 920 +- package.json | 18 +- 3 files changed, 35432 insertions(+), 25694 deletions(-) diff --git a/dist/index.js b/dist/index.js index 6197683..251e29b 100644 --- a/dist/index.js +++ b/dist/index.js @@ -3723,7 +3723,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.agentsStream = agentsStream; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const event_streams_js_1 = __nccwpck_require__(3835); const M = __importStar(__nccwpck_require__(312)); @@ -4367,7 +4367,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.chatStream = chatStream; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const event_streams_js_1 = __nccwpck_require__(3835); const M = __importStar(__nccwpck_require__(312)); @@ -4898,7 +4898,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.filesDownload = filesDownload; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const M = __importStar(__nccwpck_require__(312)); const schemas_js_1 = __nccwpck_require__(7055); @@ -5557,7 +5557,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fimStream = fimStream; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const encodings_js_1 = __nccwpck_require__(5125); const event_streams_js_1 = __nccwpck_require__(3835); const M = __importStar(__nccwpck_require__(312)); @@ -7055,7 +7055,7 @@ exports.stringToBytes = stringToBytes; exports.stringFromBytes = stringFromBytes; exports.stringToBase64 = stringToBase64; exports.stringFromBase64 = stringFromBase64; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); function bytesToBase64(u8arr) { return btoa(String.fromCodePoint(...u8arr)); } @@ -7566,7 +7566,7 @@ exports.envSchema = void 0; exports.env = env; exports.resetEnv = resetEnv; const dlv_js_1 = __nccwpck_require__(5541); -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.envSchema = z.object({ MISTRAL_API_KEY: z.string().optional(), MISTRAL_DEBUG: z.coerce.boolean().optional(), @@ -8619,7 +8619,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parse = parse; exports.safeParse = safeParse; exports.collectExtraKeys = collectExtraKeys; -const zod_1 = __nccwpck_require__(4809); +const zod_1 = __nccwpck_require__(2046); const sdkvalidationerror_js_1 = __nccwpck_require__(2169); const fp_js_1 = __nccwpck_require__(1443); /** @@ -9173,7 +9173,7 @@ exports.agentsCompletionRequestToolChoiceToJSON = agentsCompletionRequestToolCho exports.agentsCompletionRequestToolChoiceFromJSON = agentsCompletionRequestToolChoiceFromJSON; exports.agentsCompletionRequestToJSON = agentsCompletionRequestToJSON; exports.agentsCompletionRequestFromJSON = agentsCompletionRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -9406,7 +9406,7 @@ exports.agentsCompletionStreamRequestToolChoiceToJSON = agentsCompletionStreamRe exports.agentsCompletionStreamRequestToolChoiceFromJSON = agentsCompletionStreamRequestToolChoiceFromJSON; exports.agentsCompletionStreamRequestToJSON = agentsCompletionStreamRequestToJSON; exports.agentsCompletionStreamRequestFromJSON = agentsCompletionStreamRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -9631,7 +9631,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ApiEndpoint$ = exports.ApiEndpoint$outboundSchema = exports.ApiEndpoint$inboundSchema = exports.ApiEndpoint = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.ApiEndpoint = { RootV1ChatCompletions: "/v1/chat/completions", @@ -9700,7 +9700,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ArchiveFTModelOut$ = exports.ArchiveFTModelOut$outboundSchema = exports.ArchiveFTModelOut$inboundSchema = exports.ArchiveFTModelOutObject$ = exports.ArchiveFTModelOutObject$outboundSchema = exports.ArchiveFTModelOutObject$inboundSchema = exports.ArchiveFTModelOutObject = void 0; exports.archiveFTModelOutToJSON = archiveFTModelOutToJSON; exports.archiveFTModelOutFromJSON = archiveFTModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.ArchiveFTModelOutObject = { Model: "model", @@ -9789,7 +9789,7 @@ exports.assistantMessageContentToJSON = assistantMessageContentToJSON; exports.assistantMessageContentFromJSON = assistantMessageContentFromJSON; exports.assistantMessageToJSON = assistantMessageToJSON; exports.assistantMessageFromJSON = assistantMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); @@ -9910,7 +9910,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BaseModelCard$ = exports.BaseModelCard$outboundSchema = exports.BaseModelCard$inboundSchema = exports.Type$ = exports.Type$outboundSchema = exports.Type$inboundSchema = exports.Type = void 0; exports.baseModelCardToJSON = baseModelCardToJSON; exports.baseModelCardFromJSON = baseModelCardFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const modelcapabilities_js_1 = __nccwpck_require__(8296); @@ -10029,7 +10029,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchError$ = exports.BatchError$outboundSchema = exports.BatchError$inboundSchema = void 0; exports.batchErrorToJSON = batchErrorToJSON; exports.batchErrorFromJSON = batchErrorFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.BatchError$inboundSchema = z.object({ @@ -10096,7 +10096,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobIn$ = exports.BatchJobIn$outboundSchema = exports.BatchJobIn$inboundSchema = void 0; exports.batchJobInToJSON = batchJobInToJSON; exports.batchJobInFromJSON = batchJobInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const apiendpoint_js_1 = __nccwpck_require__(6238); @@ -10181,7 +10181,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobOut$ = exports.BatchJobOut$outboundSchema = exports.BatchJobOut$inboundSchema = exports.BatchJobOutObject$ = exports.BatchJobOutObject$outboundSchema = exports.BatchJobOutObject$inboundSchema = exports.BatchJobOutObject = void 0; exports.batchJobOutToJSON = batchJobOutToJSON; exports.batchJobOutFromJSON = batchJobOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const batcherror_js_1 = __nccwpck_require__(7357); @@ -10325,7 +10325,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobsOut$ = exports.BatchJobsOut$outboundSchema = exports.BatchJobsOut$inboundSchema = exports.BatchJobsOutObject$ = exports.BatchJobsOutObject$outboundSchema = exports.BatchJobsOutObject$inboundSchema = exports.BatchJobsOutObject = void 0; exports.batchJobsOutToJSON = batchJobsOutToJSON; exports.batchJobsOutFromJSON = batchJobsOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const batchjobout_js_1 = __nccwpck_require__(834); exports.BatchJobsOutObject = { @@ -10411,7 +10411,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.BatchJobStatus$ = exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema = exports.BatchJobStatus = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.BatchJobStatus = { Queued: "QUEUED", Running: "RUNNING", @@ -10480,7 +10480,7 @@ exports.chatClassificationRequestInputsToJSON = chatClassificationRequestInputsT exports.chatClassificationRequestInputsFromJSON = chatClassificationRequestInputsFromJSON; exports.chatClassificationRequestToJSON = chatClassificationRequestToJSON; exports.chatClassificationRequestFromJSON = chatClassificationRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -10793,7 +10793,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChatCompletionChoice$ = exports.ChatCompletionChoice$outboundSchema = exports.ChatCompletionChoice$inboundSchema = exports.FinishReason$ = exports.FinishReason$outboundSchema = exports.FinishReason$inboundSchema = exports.FinishReason = void 0; exports.chatCompletionChoiceToJSON = chatCompletionChoiceToJSON; exports.chatCompletionChoiceFromJSON = chatCompletionChoiceFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const enums_js_1 = __nccwpck_require__(9271); @@ -10908,7 +10908,7 @@ exports.chatCompletionRequestToolChoiceToJSON = chatCompletionRequestToolChoiceT exports.chatCompletionRequestToolChoiceFromJSON = chatCompletionRequestToolChoiceFromJSON; exports.chatCompletionRequestToJSON = chatCompletionRequestToJSON; exports.chatCompletionRequestFromJSON = chatCompletionRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -11144,7 +11144,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ChatCompletionResponse$ = exports.ChatCompletionResponse$outboundSchema = exports.ChatCompletionResponse$inboundSchema = void 0; exports.chatCompletionResponseToJSON = chatCompletionResponseToJSON; exports.chatCompletionResponseFromJSON = chatCompletionResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const chatcompletionchoice_js_1 = __nccwpck_require__(208); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -11227,7 +11227,7 @@ exports.chatCompletionStreamRequestToolChoiceToJSON = chatCompletionStreamReques exports.chatCompletionStreamRequestToolChoiceFromJSON = chatCompletionStreamRequestToolChoiceFromJSON; exports.chatCompletionStreamRequestToJSON = chatCompletionStreamRequestToJSON; exports.chatCompletionStreamRequestFromJSON = chatCompletionStreamRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const assistantmessage_js_1 = __nccwpck_require__(9240); @@ -11462,7 +11462,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CheckpointOut$ = exports.CheckpointOut$outboundSchema = exports.CheckpointOut$inboundSchema = void 0; exports.checkpointOutToJSON = checkpointOutToJSON; exports.checkpointOutFromJSON = checkpointOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const metricout_js_1 = __nccwpck_require__(427); @@ -11543,7 +11543,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ClassificationObject$ = exports.ClassificationObject$outboundSchema = exports.ClassificationObject$inboundSchema = void 0; exports.classificationObjectToJSON = classificationObjectToJSON; exports.classificationObjectFromJSON = classificationObjectFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -11621,7 +11621,7 @@ exports.classificationRequestInputsToJSON = classificationRequestInputsToJSON; exports.classificationRequestInputsFromJSON = classificationRequestInputsFromJSON; exports.classificationRequestToJSON = classificationRequestToJSON; exports.classificationRequestFromJSON = classificationRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -11718,7 +11718,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ClassificationResponse$ = exports.ClassificationResponse$outboundSchema = exports.ClassificationResponse$inboundSchema = void 0; exports.classificationResponseToJSON = classificationResponseToJSON; exports.classificationResponseFromJSON = classificationResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const classificationobject_js_1 = __nccwpck_require__(4480); /** @internal */ @@ -11788,7 +11788,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompletionChunk$ = exports.CompletionChunk$outboundSchema = exports.CompletionChunk$inboundSchema = void 0; exports.completionChunkToJSON = completionChunkToJSON; exports.completionChunkFromJSON = completionChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const completionresponsestreamchoice_js_1 = __nccwpck_require__(9937); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -11865,7 +11865,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompletionEvent$ = exports.CompletionEvent$outboundSchema = exports.CompletionEvent$inboundSchema = void 0; exports.completionEventToJSON = completionEventToJSON; exports.completionEventFromJSON = completionEventFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const completionchunk_js_1 = __nccwpck_require__(2804); /** @internal */ @@ -11942,7 +11942,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.CompletionResponseStreamChoice$ = exports.CompletionResponseStreamChoice$outboundSchema = exports.CompletionResponseStreamChoice$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason$ = exports.CompletionResponseStreamChoiceFinishReason$outboundSchema = exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason = void 0; exports.completionResponseStreamChoiceToJSON = completionResponseStreamChoiceToJSON; exports.completionResponseStreamChoiceFromJSON = completionResponseStreamChoiceFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const enums_js_1 = __nccwpck_require__(9271); @@ -12050,7 +12050,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ContentChunk$ = exports.ContentChunk$outboundSchema = exports.ContentChunk$inboundSchema = void 0; exports.contentChunkToJSON = contentChunkToJSON; exports.contentChunkFromJSON = contentChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const imageurlchunk_js_1 = __nccwpck_require__(4316); const referencechunk_js_1 = __nccwpck_require__(7809); @@ -12130,7 +12130,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteFileOut$ = exports.DeleteFileOut$outboundSchema = exports.DeleteFileOut$inboundSchema = void 0; exports.deleteFileOutToJSON = deleteFileOutToJSON; exports.deleteFileOutFromJSON = deleteFileOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.DeleteFileOut$inboundSchema = z.object({ @@ -12199,7 +12199,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteModelOut$ = exports.DeleteModelOut$outboundSchema = exports.DeleteModelOut$inboundSchema = void 0; exports.deleteModelOutToJSON = deleteModelOutToJSON; exports.deleteModelOutFromJSON = deleteModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.DeleteModelOut$inboundSchema = z.object({ @@ -12270,7 +12270,7 @@ exports.contentToJSON = contentToJSON; exports.contentFromJSON = contentFromJSON; exports.deltaMessageToJSON = deltaMessageToJSON; exports.deltaMessageFromJSON = deltaMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); @@ -12375,7 +12375,7 @@ exports.detailedJobOutRepositoriesToJSON = detailedJobOutRepositoriesToJSON; exports.detailedJobOutRepositoriesFromJSON = detailedJobOutRepositoriesFromJSON; exports.detailedJobOutToJSON = detailedJobOutToJSON; exports.detailedJobOutFromJSON = detailedJobOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const checkpointout_js_1 = __nccwpck_require__(1225); @@ -12596,7 +12596,7 @@ exports.inputsToJSON = inputsToJSON; exports.inputsFromJSON = inputsFromJSON; exports.embeddingRequestToJSON = embeddingRequestToJSON; exports.embeddingRequestFromJSON = embeddingRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -12698,7 +12698,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EmbeddingResponse$ = exports.EmbeddingResponse$outboundSchema = exports.EmbeddingResponse$inboundSchema = void 0; exports.embeddingResponseToJSON = embeddingResponseToJSON; exports.embeddingResponseFromJSON = embeddingResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const embeddingresponsedata_js_1 = __nccwpck_require__(2101); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -12773,7 +12773,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EmbeddingResponseData$ = exports.EmbeddingResponseData$outboundSchema = exports.EmbeddingResponseData$inboundSchema = void 0; exports.embeddingResponseDataToJSON = embeddingResponseDataToJSON; exports.embeddingResponseDataFromJSON = embeddingResponseDataFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.EmbeddingResponseData$inboundSchema = z.object({ @@ -12842,7 +12842,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.EventOut$ = exports.EventOut$outboundSchema = exports.EventOut$inboundSchema = void 0; exports.eventOutToJSON = eventOutToJSON; exports.eventOutFromJSON = eventOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -12918,7 +12918,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilePurpose$ = exports.FilePurpose$outboundSchema = exports.FilePurpose$inboundSchema = exports.FilePurpose = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.FilePurpose = { FineTune: "fine-tune", @@ -12984,7 +12984,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileSchema$ = exports.FileSchema$outboundSchema = exports.FileSchema$inboundSchema = void 0; exports.fileSchemaToJSON = fileSchemaToJSON; exports.fileSchemaFromJSON = fileSchemaFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const filepurpose_js_1 = __nccwpck_require__(1087); @@ -13081,7 +13081,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileSignedURL$ = exports.FileSignedURL$outboundSchema = exports.FileSignedURL$inboundSchema = void 0; exports.fileSignedURLToJSON = fileSignedURLToJSON; exports.fileSignedURLFromJSON = fileSignedURLFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.FileSignedURL$inboundSchema = z.object({ @@ -13148,7 +13148,7 @@ exports.fimCompletionRequestStopToJSON = fimCompletionRequestStopToJSON; exports.fimCompletionRequestStopFromJSON = fimCompletionRequestStopFromJSON; exports.fimCompletionRequestToJSON = fimCompletionRequestToJSON; exports.fimCompletionRequestFromJSON = fimCompletionRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -13267,7 +13267,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FIMCompletionResponse$ = exports.FIMCompletionResponse$outboundSchema = exports.FIMCompletionResponse$inboundSchema = void 0; exports.fimCompletionResponseToJSON = fimCompletionResponseToJSON; exports.fimCompletionResponseFromJSON = fimCompletionResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const chatcompletionchoice_js_1 = __nccwpck_require__(208); const usageinfo_js_1 = __nccwpck_require__(1804); @@ -13346,7 +13346,7 @@ exports.fimCompletionStreamRequestStopToJSON = fimCompletionStreamRequestStopToJ exports.fimCompletionStreamRequestStopFromJSON = fimCompletionStreamRequestStopFromJSON; exports.fimCompletionStreamRequestToJSON = fimCompletionStreamRequestToJSON; exports.fimCompletionStreamRequestFromJSON = fimCompletionStreamRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -13465,7 +13465,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTModelCapabilitiesOut$ = exports.FTModelCapabilitiesOut$outboundSchema = exports.FTModelCapabilitiesOut$inboundSchema = void 0; exports.ftModelCapabilitiesOutToJSON = ftModelCapabilitiesOutToJSON; exports.ftModelCapabilitiesOutFromJSON = ftModelCapabilitiesOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -13551,7 +13551,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTModelCard$ = exports.FTModelCard$outboundSchema = exports.FTModelCard$inboundSchema = exports.FTModelCardType$ = exports.FTModelCardType$outboundSchema = exports.FTModelCardType$inboundSchema = exports.FTModelCardType = void 0; exports.ftModelCardToJSON = ftModelCardToJSON; exports.ftModelCardFromJSON = ftModelCardFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const modelcapabilities_js_1 = __nccwpck_require__(8296); @@ -13676,7 +13676,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTModelOut$ = exports.FTModelOut$outboundSchema = exports.FTModelOut$inboundSchema = exports.FTModelOutObject$ = exports.FTModelOutObject$outboundSchema = exports.FTModelOutObject$inboundSchema = exports.FTModelOutObject = void 0; exports.ftModelOutToJSON = ftModelOutToJSON; exports.ftModelOutFromJSON = ftModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const ftmodelcapabilitiesout_js_1 = __nccwpck_require__(7296); @@ -13793,7 +13793,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FunctionT$ = exports.FunctionT$outboundSchema = exports.FunctionT$inboundSchema = void 0; exports.functionToJSON = functionToJSON; exports.functionFromJSON = functionFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.FunctionT$inboundSchema = z.object({ @@ -13864,7 +13864,7 @@ exports.argumentsToJSON = argumentsToJSON; exports.argumentsFromJSON = argumentsFromJSON; exports.functionCallToJSON = functionCallToJSON; exports.functionCallFromJSON = functionCallFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.Arguments$inboundSchema = z.union([z.record(z.any()), z.string()]); @@ -13952,7 +13952,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FunctionName$ = exports.FunctionName$outboundSchema = exports.FunctionName$inboundSchema = void 0; exports.functionNameToJSON = functionNameToJSON; exports.functionNameFromJSON = functionNameFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.FunctionName$inboundSchema = z.object({ @@ -14017,7 +14017,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GithubRepositoryIn$ = exports.GithubRepositoryIn$outboundSchema = exports.GithubRepositoryIn$inboundSchema = exports.GithubRepositoryInType$ = exports.GithubRepositoryInType$outboundSchema = exports.GithubRepositoryInType$inboundSchema = exports.GithubRepositoryInType = void 0; exports.githubRepositoryInToJSON = githubRepositoryInToJSON; exports.githubRepositoryInFromJSON = githubRepositoryInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.GithubRepositoryInType = { Github: "github", @@ -14110,7 +14110,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.GithubRepositoryOut$ = exports.GithubRepositoryOut$outboundSchema = exports.GithubRepositoryOut$inboundSchema = exports.GithubRepositoryOutType$ = exports.GithubRepositoryOutType$outboundSchema = exports.GithubRepositoryOutType$inboundSchema = exports.GithubRepositoryOutType = void 0; exports.githubRepositoryOutToJSON = githubRepositoryOutToJSON; exports.githubRepositoryOutFromJSON = githubRepositoryOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.GithubRepositoryOutType = { @@ -14212,7 +14212,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ImageURL$ = exports.ImageURL$outboundSchema = exports.ImageURL$inboundSchema = void 0; exports.imageURLToJSON = imageURLToJSON; exports.imageURLFromJSON = imageURLFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.ImageURL$inboundSchema = z.object({ @@ -14281,7 +14281,7 @@ exports.imageURLChunkImageURLToJSON = imageURLChunkImageURLToJSON; exports.imageURLChunkImageURLFromJSON = imageURLChunkImageURLFromJSON; exports.imageURLChunkToJSON = imageURLChunkToJSON; exports.imageURLChunkFromJSON = imageURLChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const imageurl_js_1 = __nccwpck_require__(7893); @@ -14510,7 +14510,7 @@ exports.jobInRepositoriesToJSON = jobInRepositoriesToJSON; exports.jobInRepositoriesFromJSON = jobInRepositoriesFromJSON; exports.jobInToJSON = jobInToJSON; exports.jobInFromJSON = jobInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const githubrepositoryin_js_1 = __nccwpck_require__(4323); @@ -14650,7 +14650,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobMetadataOut$ = exports.JobMetadataOut$outboundSchema = exports.JobMetadataOut$inboundSchema = void 0; exports.jobMetadataOutToJSON = jobMetadataOutToJSON; exports.jobMetadataOutFromJSON = jobMetadataOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -14750,7 +14750,7 @@ exports.repositoriesToJSON = repositoriesToJSON; exports.repositoriesFromJSON = repositoriesFromJSON; exports.jobOutToJSON = jobOutToJSON; exports.jobOutFromJSON = jobOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const githubrepositoryout_js_1 = __nccwpck_require__(2410); @@ -14972,7 +14972,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsOut$ = exports.JobsOut$outboundSchema = exports.JobsOut$inboundSchema = exports.JobsOutObject$ = exports.JobsOutObject$outboundSchema = exports.JobsOutObject$inboundSchema = exports.JobsOutObject = void 0; exports.jobsOutToJSON = jobsOutToJSON; exports.jobsOutFromJSON = jobsOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const jobout_js_1 = __nccwpck_require__(6186); exports.JobsOutObject = { @@ -15060,7 +15060,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.LegacyJobMetadataOut$ = exports.LegacyJobMetadataOut$outboundSchema = exports.LegacyJobMetadataOut$inboundSchema = exports.LegacyJobMetadataOutObject$ = exports.LegacyJobMetadataOutObject$outboundSchema = exports.LegacyJobMetadataOutObject$inboundSchema = exports.LegacyJobMetadataOutObject = void 0; exports.legacyJobMetadataOutToJSON = legacyJobMetadataOutToJSON; exports.legacyJobMetadataOutFromJSON = legacyJobMetadataOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.LegacyJobMetadataOutObject = { @@ -15186,7 +15186,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ListFilesOut$ = exports.ListFilesOut$outboundSchema = exports.ListFilesOut$inboundSchema = void 0; exports.listFilesOutToJSON = listFilesOutToJSON; exports.listFilesOutFromJSON = listFilesOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const fileschema_js_1 = __nccwpck_require__(5662); /** @internal */ @@ -15256,7 +15256,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.MetricOut$ = exports.MetricOut$outboundSchema = exports.MetricOut$inboundSchema = void 0; exports.metricOutToJSON = metricOutToJSON; exports.metricOutFromJSON = metricOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -15338,7 +15338,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ModelCapabilities$ = exports.ModelCapabilities$outboundSchema = exports.ModelCapabilities$inboundSchema = void 0; exports.modelCapabilitiesToJSON = modelCapabilitiesToJSON; exports.modelCapabilitiesFromJSON = modelCapabilitiesFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -15428,7 +15428,7 @@ exports.dataToJSON = dataToJSON; exports.dataFromJSON = dataFromJSON; exports.modelListToJSON = modelListToJSON; exports.modelListFromJSON = modelListFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const basemodelcard_js_1 = __nccwpck_require__(579); const ftmodelcard_js_1 = __nccwpck_require__(3942); @@ -15547,7 +15547,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ReferenceChunk$ = exports.ReferenceChunk$outboundSchema = exports.ReferenceChunk$inboundSchema = exports.ReferenceChunkType$ = exports.ReferenceChunkType$outboundSchema = exports.ReferenceChunkType$inboundSchema = exports.ReferenceChunkType = void 0; exports.referenceChunkToJSON = referenceChunkToJSON; exports.referenceChunkFromJSON = referenceChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.ReferenceChunkType = { @@ -15641,7 +15641,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResponseFormat$ = exports.ResponseFormat$outboundSchema = exports.ResponseFormat$inboundSchema = void 0; exports.responseFormatToJSON = responseFormatToJSON; exports.responseFormatFromJSON = responseFormatFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const responseformats_js_1 = __nccwpck_require__(6190); /** @internal */ @@ -15705,7 +15705,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ResponseFormats$ = exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema = exports.ResponseFormats = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); /** * An object specifying the format that the model must output. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is in JSON. When using JSON mode you MUST also instruct the model to produce JSON yourself with a system or a user message. */ @@ -15766,7 +15766,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.RetrieveFileOut$ = exports.RetrieveFileOut$outboundSchema = exports.RetrieveFileOut$inboundSchema = void 0; exports.retrieveFileOutToJSON = retrieveFileOutToJSON; exports.retrieveFileOutFromJSON = retrieveFileOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const filepurpose_js_1 = __nccwpck_require__(1087); @@ -15863,7 +15863,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SampleType$ = exports.SampleType$outboundSchema = exports.SampleType$inboundSchema = exports.SampleType = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.SampleType = { Pretrain: "pretrain", @@ -15932,7 +15932,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Security$ = exports.Security$outboundSchema = exports.Security$inboundSchema = void 0; exports.securityToJSON = securityToJSON; exports.securityFromJSON = securityFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16004,7 +16004,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Source$ = exports.Source$outboundSchema = exports.Source$inboundSchema = exports.Source = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.Source = { Upload: "upload", @@ -16074,7 +16074,7 @@ exports.systemMessageContentToJSON = systemMessageContentToJSON; exports.systemMessageContentFromJSON = systemMessageContentFromJSON; exports.systemMessageToJSON = systemMessageToJSON; exports.systemMessageFromJSON = systemMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const textchunk_js_1 = __nccwpck_require__(599); exports.Role = { @@ -16181,7 +16181,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TextChunk$ = exports.TextChunk$outboundSchema = exports.TextChunk$inboundSchema = exports.TextChunkType$ = exports.TextChunkType$outboundSchema = exports.TextChunkType$inboundSchema = exports.TextChunkType = void 0; exports.textChunkToJSON = textChunkToJSON; exports.textChunkFromJSON = textChunkFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.TextChunkType = { Text: "text", @@ -16266,7 +16266,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Tool$ = exports.Tool$outboundSchema = exports.Tool$inboundSchema = void 0; exports.toolToJSON = toolToJSON; exports.toolFromJSON = toolFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const function_js_1 = __nccwpck_require__(6603); const tooltypes_js_1 = __nccwpck_require__(6340); @@ -16336,7 +16336,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolCall$ = exports.ToolCall$outboundSchema = exports.ToolCall$inboundSchema = void 0; exports.toolCallToJSON = toolCallToJSON; exports.toolCallFromJSON = toolCallFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const functioncall_js_1 = __nccwpck_require__(347); const tooltypes_js_1 = __nccwpck_require__(6340); @@ -16407,7 +16407,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolChoice$ = exports.ToolChoice$outboundSchema = exports.ToolChoice$inboundSchema = void 0; exports.toolChoiceToJSON = toolChoiceToJSON; exports.toolChoiceFromJSON = toolChoiceFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const functionname_js_1 = __nccwpck_require__(9636); const tooltypes_js_1 = __nccwpck_require__(6340); @@ -16474,7 +16474,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolChoiceEnum$ = exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema = exports.ToolChoiceEnum = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.ToolChoiceEnum = { Auto: "auto", None: "none", @@ -16536,7 +16536,7 @@ exports.toolMessageContentToJSON = toolMessageContentToJSON; exports.toolMessageContentFromJSON = toolMessageContentFromJSON; exports.toolMessageToJSON = toolMessageToJSON; exports.toolMessageFromJSON = toolMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); @@ -16654,7 +16654,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ToolTypes$ = exports.ToolTypes$outboundSchema = exports.ToolTypes$inboundSchema = exports.ToolTypes = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const enums_js_1 = __nccwpck_require__(9271); exports.ToolTypes = { Function: "function", @@ -16719,7 +16719,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TrainingFile$ = exports.TrainingFile$outboundSchema = exports.TrainingFile$inboundSchema = void 0; exports.trainingFileToJSON = trainingFileToJSON; exports.trainingFileFromJSON = trainingFileFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16795,7 +16795,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TrainingParameters$ = exports.TrainingParameters$outboundSchema = exports.TrainingParameters$inboundSchema = void 0; exports.trainingParametersToJSON = trainingParametersToJSON; exports.trainingParametersFromJSON = trainingParametersFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16891,7 +16891,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TrainingParametersIn$ = exports.TrainingParametersIn$outboundSchema = exports.TrainingParametersIn$inboundSchema = void 0; exports.trainingParametersInToJSON = trainingParametersInToJSON; exports.trainingParametersInFromJSON = trainingParametersInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -16987,7 +16987,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UnarchiveFTModelOut$ = exports.UnarchiveFTModelOut$outboundSchema = exports.UnarchiveFTModelOut$inboundSchema = exports.UnarchiveFTModelOutObject$ = exports.UnarchiveFTModelOutObject$outboundSchema = exports.UnarchiveFTModelOutObject$inboundSchema = exports.UnarchiveFTModelOutObject = void 0; exports.unarchiveFTModelOutToJSON = unarchiveFTModelOutToJSON; exports.unarchiveFTModelOutFromJSON = unarchiveFTModelOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); exports.UnarchiveFTModelOutObject = { Model: "model", @@ -17074,7 +17074,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UpdateFTModelIn$ = exports.UpdateFTModelIn$outboundSchema = exports.UpdateFTModelIn$inboundSchema = void 0; exports.updateFTModelInToJSON = updateFTModelInToJSON; exports.updateFTModelInFromJSON = updateFTModelInFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.UpdateFTModelIn$inboundSchema = z.object({ @@ -17141,7 +17141,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UploadFileOut$ = exports.UploadFileOut$outboundSchema = exports.UploadFileOut$inboundSchema = void 0; exports.uploadFileOutToJSON = uploadFileOutToJSON; exports.uploadFileOutFromJSON = uploadFileOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const filepurpose_js_1 = __nccwpck_require__(1087); @@ -17238,7 +17238,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.UsageInfo$ = exports.UsageInfo$outboundSchema = exports.UsageInfo$inboundSchema = void 0; exports.usageInfoToJSON = usageInfoToJSON; exports.usageInfoFromJSON = usageInfoFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -17322,7 +17322,7 @@ exports.userMessageContentToJSON = userMessageContentToJSON; exports.userMessageContentFromJSON = userMessageContentFromJSON; exports.userMessageToJSON = userMessageToJSON; exports.userMessageFromJSON = userMessageFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const contentchunk_js_1 = __nccwpck_require__(2889); exports.UserMessageRole = { @@ -17431,7 +17431,7 @@ exports.locToJSON = locToJSON; exports.locFromJSON = locFromJSON; exports.validationErrorToJSON = validationErrorToJSON; exports.validationErrorFromJSON = validationErrorFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ exports.Loc$inboundSchema = z.union([z.string(), z.number().int()]); @@ -17522,7 +17522,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WandbIntegration$ = exports.WandbIntegration$outboundSchema = exports.WandbIntegration$inboundSchema = exports.WandbIntegrationType$ = exports.WandbIntegrationType$outboundSchema = exports.WandbIntegrationType$inboundSchema = exports.WandbIntegrationType = void 0; exports.wandbIntegrationToJSON = wandbIntegrationToJSON; exports.wandbIntegrationFromJSON = wandbIntegrationFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.WandbIntegrationType = { @@ -17624,7 +17624,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.WandbIntegrationOut$ = exports.WandbIntegrationOut$outboundSchema = exports.WandbIntegrationOut$inboundSchema = exports.WandbIntegrationOutType$ = exports.WandbIntegrationOutType$outboundSchema = exports.WandbIntegrationOutType$inboundSchema = exports.WandbIntegrationOutType = void 0; exports.wandbIntegrationOutToJSON = wandbIntegrationOutToJSON; exports.wandbIntegrationOutFromJSON = wandbIntegrationOutFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); exports.WandbIntegrationOutType = { @@ -17804,7 +17804,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HTTPValidationError$ = exports.HTTPValidationError$outboundSchema = exports.HTTPValidationError$inboundSchema = exports.HTTPValidationError = void 0; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const components = __importStar(__nccwpck_require__(8471)); class HTTPValidationError extends Error { constructor(err) { @@ -17937,7 +17937,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.SDKValidationError = void 0; exports.formatZodError = formatZodError; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); class SDKValidationError extends Error { constructor(message, cause, rawValue) { super(`${message}: ${cause}`); @@ -18049,7 +18049,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DeleteModelV1ModelsModelIdDeleteRequest$ = exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = exports.DeleteModelV1ModelsModelIdDeleteRequest$inboundSchema = void 0; exports.deleteModelV1ModelsModelIdDeleteRequestToJSON = deleteModelV1ModelsModelIdDeleteRequestToJSON; exports.deleteModelV1ModelsModelIdDeleteRequestFromJSON = deleteModelV1ModelsModelIdDeleteRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18123,7 +18123,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesDeleteFileRequest$ = exports.FilesApiRoutesDeleteFileRequest$outboundSchema = exports.FilesApiRoutesDeleteFileRequest$inboundSchema = void 0; exports.filesApiRoutesDeleteFileRequestToJSON = filesApiRoutesDeleteFileRequestToJSON; exports.filesApiRoutesDeleteFileRequestFromJSON = filesApiRoutesDeleteFileRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18197,7 +18197,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesDownloadFileRequest$ = exports.FilesApiRoutesDownloadFileRequest$outboundSchema = exports.FilesApiRoutesDownloadFileRequest$inboundSchema = void 0; exports.filesApiRoutesDownloadFileRequestToJSON = filesApiRoutesDownloadFileRequestToJSON; exports.filesApiRoutesDownloadFileRequestFromJSON = filesApiRoutesDownloadFileRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18271,7 +18271,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesGetSignedUrlRequest$ = exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = exports.FilesApiRoutesGetSignedUrlRequest$inboundSchema = void 0; exports.filesApiRoutesGetSignedUrlRequestToJSON = filesApiRoutesGetSignedUrlRequestToJSON; exports.filesApiRoutesGetSignedUrlRequestFromJSON = filesApiRoutesGetSignedUrlRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18347,7 +18347,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesListFilesRequest$ = exports.FilesApiRoutesListFilesRequest$outboundSchema = exports.FilesApiRoutesListFilesRequest$inboundSchema = void 0; exports.filesApiRoutesListFilesRequestToJSON = filesApiRoutesListFilesRequestToJSON; exports.filesApiRoutesListFilesRequestFromJSON = filesApiRoutesListFilesRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -18436,7 +18436,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FilesApiRoutesRetrieveFileRequest$ = exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = exports.FilesApiRoutesRetrieveFileRequest$inboundSchema = void 0; exports.filesApiRoutesRetrieveFileRequestToJSON = filesApiRoutesRetrieveFileRequestToJSON; exports.filesApiRoutesRetrieveFileRequestFromJSON = filesApiRoutesRetrieveFileRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18512,7 +18512,7 @@ exports.fileToJSON = fileToJSON; exports.fileFromJSON = fileFromJSON; exports.filesApiRoutesUploadFileMultiPartBodyParamsToJSON = filesApiRoutesUploadFileMultiPartBodyParamsToJSON; exports.filesApiRoutesUploadFileMultiPartBodyParamsFromJSON = filesApiRoutesUploadFileMultiPartBodyParamsFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const blobs_js_1 = __nccwpck_require__(1057); const components = __importStar(__nccwpck_require__(8471)); @@ -18664,7 +18664,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesBatchCancelBatchJobRequest$ = exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = exports.JobsApiRoutesBatchCancelBatchJobRequest$inboundSchema = void 0; exports.jobsApiRoutesBatchCancelBatchJobRequestToJSON = jobsApiRoutesBatchCancelBatchJobRequestToJSON; exports.jobsApiRoutesBatchCancelBatchJobRequestFromJSON = jobsApiRoutesBatchCancelBatchJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18738,7 +18738,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesBatchGetBatchJobRequest$ = exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = exports.JobsApiRoutesBatchGetBatchJobRequest$inboundSchema = void 0; exports.jobsApiRoutesBatchGetBatchJobRequestToJSON = jobsApiRoutesBatchGetBatchJobRequestToJSON; exports.jobsApiRoutesBatchGetBatchJobRequestFromJSON = jobsApiRoutesBatchGetBatchJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18812,7 +18812,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesBatchGetBatchJobsRequest$ = exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = exports.JobsApiRoutesBatchGetBatchJobsRequest$inboundSchema = void 0; exports.jobsApiRoutesBatchGetBatchJobsRequestToJSON = jobsApiRoutesBatchGetBatchJobsRequestToJSON; exports.jobsApiRoutesBatchGetBatchJobsRequestFromJSON = jobsApiRoutesBatchGetBatchJobsRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -18903,7 +18903,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$ = exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON; exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestFromJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -18977,7 +18977,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$ = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON; exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestFromJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19051,7 +19051,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$ = exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$outboundSchema = exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = void 0; exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseToJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseToJSON; exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); /** @internal */ @@ -19119,7 +19119,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$ = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON; exports.jobsApiRoutesFineTuningGetFineTuningJobRequestFromJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19193,7 +19193,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$ = exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$inboundSchema = exports.Status$ = exports.Status$outboundSchema = exports.Status$inboundSchema = exports.Status = void 0; exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON; exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestFromJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @@ -19323,7 +19323,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$ = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON; exports.jobsApiRoutesFineTuningStartFineTuningJobRequestFromJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19397,7 +19397,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$ = exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON; exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestFromJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); /** @internal */ @@ -19471,7 +19471,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$ = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$inboundSchema = void 0; exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON; exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestFromJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -19552,7 +19552,7 @@ exports.retrieveModelV1ModelsModelIdGetRequestToJSON = retrieveModelV1ModelsMode exports.retrieveModelV1ModelsModelIdGetRequestFromJSON = retrieveModelV1ModelsModelIdGetRequestFromJSON; exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetToJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetToJSON; exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); const primitives_js_1 = __nccwpck_require__(6961); const schemas_js_1 = __nccwpck_require__(7055); const components = __importStar(__nccwpck_require__(8471)); @@ -20220,7 +20220,7 @@ var __importStar = (this && this.__importStar) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.blobLikeSchema = void 0; exports.isBlobLike = isBlobLike; -const z = __importStar(__nccwpck_require__(4809)); +const z = __importStar(__nccwpck_require__(2046)); exports.blobLikeSchema = z.custom(isBlobLike, { message: "expected a Blob, File or Blob-like object", fatal: true, @@ -33051,6 +33051,8 @@ RetryOperation.prototype.mainError = function() { /***/ 9379: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const ANY = Symbol('SemVer ANY') // hoisted class for cyclic dependency class Comparator { @@ -33199,6 +33201,8 @@ const Range = __nccwpck_require__(6782) /***/ 6782: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SPACE_CHARACTERS = /\s+/g // hoisted class for cyclic dependency @@ -33760,6 +33764,8 @@ const testSet = (set, version, options) => { /***/ 7163: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const debug = __nccwpck_require__(1159) const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101) const { safeRe: re, t } = __nccwpck_require__(5471) @@ -33772,7 +33778,7 @@ class SemVer { if (version instanceof SemVer) { if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { + version.includePrerelease === !!options.includePrerelease) { return version } else { version = version.version @@ -33938,6 +33944,19 @@ class SemVer { // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } + switch (release) { case 'premajor': this.prerelease.length = 0 @@ -33968,6 +33987,12 @@ class SemVer { } this.inc('pre', identifier, identifierBase) break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break case 'major': // If this is a pre-major version, bump up to the same major version. @@ -34011,10 +34036,6 @@ class SemVer { case 'pre': { const base = Number(identifierBase) ? 1 : 0 - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } - if (this.prerelease.length === 0) { this.prerelease = [base] } else { @@ -34069,6 +34090,8 @@ module.exports = SemVer /***/ 1799: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const parse = __nccwpck_require__(6353) const clean = (version, options) => { const s = parse(version.trim().replace(/^[=v]+/, ''), options) @@ -34082,6 +34105,8 @@ module.exports = clean /***/ 8646: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const eq = __nccwpck_require__(5082) const neq = __nccwpck_require__(4974) const gt = __nccwpck_require__(6599) @@ -34141,6 +34166,8 @@ module.exports = cmp /***/ 5385: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const parse = __nccwpck_require__(6353) const { safeRe: re, t } = __nccwpck_require__(5471) @@ -34208,6 +34235,8 @@ module.exports = coerce /***/ 7648: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const compareBuild = (a, b, loose) => { const versionA = new SemVer(a, loose) @@ -34222,6 +34251,8 @@ module.exports = compareBuild /***/ 6874: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const compareLoose = (a, b) => compare(a, b, true) module.exports = compareLoose @@ -34232,6 +34263,8 @@ module.exports = compareLoose /***/ 8469: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const compare = (a, b, loose) => new SemVer(a, loose).compare(new SemVer(b, loose)) @@ -34244,6 +34277,8 @@ module.exports = compare /***/ 711: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const parse = __nccwpck_require__(6353) const diff = (version1, version2) => { @@ -34273,20 +34308,13 @@ const diff = (version1, version2) => { return 'major' } - // Otherwise it can be determined by checking the high version - - if (highVersion.patch) { - // anything higher than a patch bump would result in the wrong version + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } return 'patch' } - - if (highVersion.minor) { - // anything higher than a minor bump would result in the wrong version - return 'minor' - } - - // bumping major/minor/patch all have same result - return 'major' } // add the `pre` prefix if we are going to a prerelease version @@ -34316,6 +34344,8 @@ module.exports = diff /***/ 5082: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const eq = (a, b, loose) => compare(a, b, loose) === 0 module.exports = eq @@ -34326,6 +34356,8 @@ module.exports = eq /***/ 6599: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const gt = (a, b, loose) => compare(a, b, loose) > 0 module.exports = gt @@ -34336,6 +34368,8 @@ module.exports = gt /***/ 1236: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const gte = (a, b, loose) => compare(a, b, loose) >= 0 module.exports = gte @@ -34346,6 +34380,8 @@ module.exports = gte /***/ 2338: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const inc = (version, release, options, identifier, identifierBase) => { @@ -34372,6 +34408,8 @@ module.exports = inc /***/ 3872: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const lt = (a, b, loose) => compare(a, b, loose) < 0 module.exports = lt @@ -34382,6 +34420,8 @@ module.exports = lt /***/ 6717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const lte = (a, b, loose) => compare(a, b, loose) <= 0 module.exports = lte @@ -34392,6 +34432,8 @@ module.exports = lte /***/ 8511: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const major = (a, loose) => new SemVer(a, loose).major module.exports = major @@ -34402,6 +34444,8 @@ module.exports = major /***/ 2603: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const minor = (a, loose) => new SemVer(a, loose).minor module.exports = minor @@ -34412,6 +34456,8 @@ module.exports = minor /***/ 4974: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const neq = (a, b, loose) => compare(a, b, loose) !== 0 module.exports = neq @@ -34422,6 +34468,8 @@ module.exports = neq /***/ 6353: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const parse = (version, options, throwErrors = false) => { if (version instanceof SemVer) { @@ -34445,6 +34493,8 @@ module.exports = parse /***/ 8756: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const patch = (a, loose) => new SemVer(a, loose).patch module.exports = patch @@ -34455,6 +34505,8 @@ module.exports = patch /***/ 5714: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const parse = __nccwpck_require__(6353) const prerelease = (version, options) => { const parsed = parse(version, options) @@ -34468,6 +34520,8 @@ module.exports = prerelease /***/ 2173: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compare = __nccwpck_require__(8469) const rcompare = (a, b, loose) => compare(b, a, loose) module.exports = rcompare @@ -34478,6 +34532,8 @@ module.exports = rcompare /***/ 7192: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compareBuild = __nccwpck_require__(7648) const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) module.exports = rsort @@ -34488,6 +34544,8 @@ module.exports = rsort /***/ 8011: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const satisfies = (version, range, options) => { try { @@ -34505,6 +34563,8 @@ module.exports = satisfies /***/ 9872: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const compareBuild = __nccwpck_require__(7648) const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) module.exports = sort @@ -34515,6 +34575,8 @@ module.exports = sort /***/ 8780: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const parse = __nccwpck_require__(6353) const valid = (version, options) => { const v = parse(version, options) @@ -34528,6 +34590,8 @@ module.exports = valid /***/ 2088: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + // just pre-load all the stuff that index.js lazily exports const internalRe = __nccwpck_require__(5471) const constants = __nccwpck_require__(5101) @@ -34624,6 +34688,8 @@ module.exports = { /***/ 5101: /***/ ((module) => { + + // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0' @@ -34666,6 +34732,8 @@ module.exports = { /***/ 1159: /***/ ((module) => { + + const debug = ( typeof process === 'object' && process.env && @@ -34682,6 +34750,8 @@ module.exports = debug /***/ 3348: /***/ ((module) => { + + const numeric = /^[0-9]+$/ const compareIdentifiers = (a, b) => { const anum = numeric.test(a) @@ -34712,6 +34782,8 @@ module.exports = { /***/ 1383: /***/ ((module) => { + + class LRUCache { constructor () { this.max = 1000 @@ -34759,6 +34831,8 @@ module.exports = LRUCache /***/ 356: /***/ ((module) => { + + // parse out just the options we care about const looseOption = Object.freeze({ loose: true }) const emptyOpts = Object.freeze({ }) @@ -34781,6 +34855,8 @@ module.exports = parseOptions /***/ 5471: /***/ ((module, exports, __nccwpck_require__) => { + + const { MAX_SAFE_COMPONENT_LENGTH, MAX_SAFE_BUILD_LENGTH, @@ -34793,6 +34869,7 @@ exports = module.exports = {} const re = exports.re = [] const safeRe = exports.safeRe = [] const src = exports.src = [] +const safeSrc = exports.safeSrc = [] const t = exports.t = {} let R = 0 @@ -34825,6 +34902,7 @@ const createToken = (name, value, isGlobal) => { debug(name, index, value) t[name] = index src[index] = value + safeSrc[index] = safe re[index] = new RegExp(value, isGlobal ? 'g' : undefined) safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) } @@ -34857,12 +34935,14 @@ createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] -}|${src[t.NONNUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] -}|${src[t.NONNUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version @@ -35005,6 +35085,8 @@ createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ 2276: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + // Determine if version is greater than all the versions possible in the range. const outside = __nccwpck_require__(280) const gtr = (version, range, options) => outside(version, range, '>', options) @@ -35016,6 +35098,8 @@ module.exports = gtr /***/ 3465: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const intersects = (r1, r2, options) => { r1 = new Range(r1, options) @@ -35030,6 +35114,8 @@ module.exports = intersects /***/ 5213: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const outside = __nccwpck_require__(280) // Determine if version is less than all the versions possible in the range const ltr = (version, range, options) => outside(version, range, '<', options) @@ -35041,6 +35127,8 @@ module.exports = ltr /***/ 5574: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Range = __nccwpck_require__(6782) @@ -35073,6 +35161,8 @@ module.exports = maxSatisfying /***/ 8595: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Range = __nccwpck_require__(6782) const minSatisfying = (versions, range, options) => { @@ -35104,6 +35194,8 @@ module.exports = minSatisfying /***/ 1866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Range = __nccwpck_require__(6782) const gt = __nccwpck_require__(6599) @@ -35172,6 +35264,8 @@ module.exports = minVersion /***/ 280: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const SemVer = __nccwpck_require__(7163) const Comparator = __nccwpck_require__(9379) const { ANY } = Comparator @@ -35259,6 +35353,8 @@ module.exports = outside /***/ 2028: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + // given a set of versions and a range, create a "simplified" range // that includes the same versions that the original range does // If the original range is shorter than the simplified one, return that. @@ -35313,6 +35409,8 @@ module.exports = (versions, range, options) => { /***/ 1489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const Comparator = __nccwpck_require__(9379) const { ANY } = Comparator @@ -35567,6 +35665,8 @@ module.exports = subset /***/ 4750: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) // Mostly just for testing and legacy API reasons @@ -35582,6 +35682,8 @@ module.exports = toComparators /***/ 4737: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + const Range = __nccwpck_require__(6782) const validRange = (range, options) => { try { @@ -61400,6378 +61502,6309 @@ function wrappy (fn, cb) { /***/ }), -/***/ 3176: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2078: +/***/ ((module) => { +module.exports = eval("require")("encoding"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; -const util_1 = __nccwpck_require__(8771); -exports.ZodIssueCode = util_1.util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -exports.quotelessJson = quotelessJson; -class ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -exports.ZodError = ZodError; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; +/***/ }), + +/***/ 2613: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); /***/ }), -/***/ 5918: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 290: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; -const en_1 = __importDefault(__nccwpck_require__(9294)); -exports.defaultErrorMap = en_1.default; -let overrideErrorMap = en_1.default; -function setErrorMap(map) { - overrideErrorMap = map; -} -exports.setErrorMap = setErrorMap; -function getErrorMap() { - return overrideErrorMap; -} -exports.getErrorMap = getErrorMap; +/***/ }), + +/***/ 181: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); /***/ }), -/***/ 9746: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 5317: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); -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 })); -__exportStar(__nccwpck_require__(5918), exports); -__exportStar(__nccwpck_require__(4640), exports); -__exportStar(__nccwpck_require__(5935), exports); -__exportStar(__nccwpck_require__(8771), exports); -__exportStar(__nccwpck_require__(5128), exports); -__exportStar(__nccwpck_require__(3176), exports); +/***/ }), + +/***/ 4236: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); /***/ }), -/***/ 189: -/***/ ((__unused_webpack_module, exports) => { +/***/ 6982: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.errorUtil = void 0; -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil || (exports.errorUtil = errorUtil = {})); +/***/ }), + +/***/ 1637: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); /***/ }), -/***/ 4640: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 4434: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; -const errors_1 = __nccwpck_require__(5918); -const en_1 = __importDefault(__nccwpck_require__(9294)); -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -exports.makeIssue = makeIssue; -exports.EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = (0, errors_1.getErrorMap)(); - const issue = (0, exports.makeIssue)({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, // contextual error map is first priority - ctx.schemaErrorMap, // then schema-bound map if available - overrideMap, // then global override map - overrideMap === en_1.default ? undefined : en_1.default, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -exports.addIssueToContext = addIssueToContext; -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return exports.INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return exports.INVALID; - if (value.status === "aborted") - return exports.INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -exports.ParseStatus = ParseStatus; -exports.INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -exports.DIRTY = DIRTY; -const OK = (value) => ({ status: "valid", value }); -exports.OK = OK; -const isAborted = (x) => x.status === "aborted"; -exports.isAborted = isAborted; -const isDirty = (x) => x.status === "dirty"; -exports.isDirty = isDirty; -const isValid = (x) => x.status === "valid"; -exports.isValid = isValid; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -exports.isAsync = isAsync; +/***/ }), + +/***/ 9896: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); /***/ }), -/***/ 5935: -/***/ ((__unused_webpack_module, exports) => { +/***/ 8611: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); -Object.defineProperty(exports, "__esModule", ({ value: true })); +/***/ }), + +/***/ 5675: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); /***/ }), -/***/ 8771: -/***/ ((__unused_webpack_module, exports) => { +/***/ 5692: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; -var util; -(function (util) { - util.assertEqual = (val) => val; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (exports.util = util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; -})(objectUtil || (exports.objectUtil = objectUtil = {})); -exports.ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return exports.ZodParsedType.undefined; - case "string": - return exports.ZodParsedType.string; - case "number": - return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; - case "boolean": - return exports.ZodParsedType.boolean; - case "function": - return exports.ZodParsedType.function; - case "bigint": - return exports.ZodParsedType.bigint; - case "symbol": - return exports.ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return exports.ZodParsedType.array; - } - if (data === null) { - return exports.ZodParsedType.null; - } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { - return exports.ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return exports.ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return exports.ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return exports.ZodParsedType.date; - } - return exports.ZodParsedType.object; - default: - return exports.ZodParsedType.unknown; - } -}; -exports.getParsedType = getParsedType; +/***/ }), + +/***/ 9278: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); /***/ }), -/***/ 4809: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 7598: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); -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 __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 })); -exports.z = void 0; -const z = __importStar(__nccwpck_require__(9746)); -exports.z = z; -__exportStar(__nccwpck_require__(9746), exports); -exports["default"] = z; +/***/ }), +/***/ 8474: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); /***/ }), -/***/ 9294: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 7075: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(8771); -const ZodError_1 = __nccwpck_require__(3176); -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodError_1.ZodIssueCode.invalid_type: - if (issue.received === util_1.ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodError_1.ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; - break; - case ZodError_1.ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; - break; - case ZodError_1.ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; - break; - case ZodError_1.ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodError_1.ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodError_1.ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodError_1.ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodError_1.ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util_1.util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodError_1.ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `smaller than or equal to` - : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodError_1.ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodError_1.ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util_1.util.assertNever(issue); - } - return { message }; -}; -exports["default"] = errorMap; +/***/ }), + +/***/ 7975: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); /***/ }), -/***/ 5128: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 857: +/***/ ((module) => { +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); -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 _ZodEnum_cache, _ZodNativeEnum_cache; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.datetimeRegex = exports.ZodType = void 0; -exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = exports.discriminatedUnion = exports.date = void 0; -const errors_1 = __nccwpck_require__(5918); -const errorUtil_1 = __nccwpck_require__(189); -const parseUtil_1 = __nccwpck_require__(4640); -const util_1 = __nccwpck_require__(8771); -const ZodError_1 = __nccwpck_require__(3176); -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } +/***/ }), + +/***/ 6928: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); + +/***/ }), + +/***/ 2987: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); + +/***/ }), + +/***/ 4876: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("punycode"); + +/***/ }), + +/***/ 3480: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); + +/***/ }), + +/***/ 2203: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); + +/***/ }), + +/***/ 3774: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); + +/***/ }), + +/***/ 3193: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); + +/***/ }), + +/***/ 3557: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); + +/***/ }), + +/***/ 4756: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); + +/***/ }), + +/***/ 7016: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); + +/***/ }), + +/***/ 9023: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); + +/***/ }), + +/***/ 8253: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); + +/***/ }), + +/***/ 8167: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); + +/***/ }), + +/***/ 3106: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); + +/***/ }), + +/***/ 7182: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const WritableStream = (__nccwpck_require__(7075).Writable) +const inherits = (__nccwpck_require__(7975).inherits) + +const StreamSearch = __nccwpck_require__(4136) + +const PartStream = __nccwpck_require__(612) +const HeaderParser = __nccwpck_require__(2271) + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) } -const handleResult = (ctx, result) => { - if ((0, parseUtil_1.isValid)(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError_1.ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; + } else { WritableStream.prototype.emit.apply(this, arguments) } } -class ZodType { - get description() { - return this._def.description; + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } } - _getType(input) { - return (0, util_1.getParsedType)(input.data); + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new parseUtil_1.ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if ((0, parseUtil_1.isAsync)(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - var _a, _b; - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async, - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return (0, parseUtil_1.isValid)(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }; - } - catch (err) { - if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true, - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_1.isValid)(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }); + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodError_1.ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); - return false; - } - else { - return true; + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data), - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; + } + }) + } } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } } -exports.ZodType = ZodType; -exports.Schema = ZodType; -exports.ZodSchema = ZodType; -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex; -// faster, simpler, safer -const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -// const ipv6Regex = -// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -// https://base64.guru/standards/base64url -const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -// simple -// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; -// no leap year validation -// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; -// with leap year validation -const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer + + +/***/ }), + +/***/ 2271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const EventEmitter = (__nccwpck_require__(8474).EventEmitter) +const inherits = (__nccwpck_require__(7975).inherits) +const getLimit = __nccwpck_require__(2393) + +const StreamSearch = __nccwpck_require__(4136) + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) } - const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; + if (isMatch) { self._finish() } + }) } -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } } -// Adapted from https://stackoverflow.com/a/3143231 -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() } -exports.datetimeRegex = datetimeRegex; -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return } - return false; + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } } -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - // Convert base64url to base64 - const base64 = header - .replace(/-/g, "+") - .replace(/_/g, "/") - .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if (!decoded.typ || !decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; + +module.exports = HeaderParser + + +/***/ }), + +/***/ 612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const inherits = (__nccwpck_require__(7975).inherits) +const ReadableStream = (__nccwpck_require__(7075).Readable) + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream + + +/***/ }), + +/***/ 4136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = (__nccwpck_require__(8474).EventEmitter) +const inherits = (__nccwpck_require__(7975).inherits) + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] } - catch (_a) { - return false; + + // No match. + + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; + } + + pos += (pos >= 0) * this._bufpos + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH + + +/***/ }), + +/***/ 9581: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const WritableStream = (__nccwpck_require__(7075).Writable) +const { inherits } = __nccwpck_require__(7975) +const Dicer = __nccwpck_require__(7182) + +const MultipartParser = __nccwpck_require__(1192) +const UrlencodedParser = __nccwpck_require__(855) +const parseParams = __nccwpck_require__(8929) + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return } - return false; + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) } -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.string, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer + + +/***/ }), + +/***/ 1192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = __nccwpck_require__(7075) +const { inherits } = __nccwpck_require__(7975) + +const Dicer = __nccwpck_require__(7182) + +const parseParams = __nccwpck_require__(8929) +const decodeText = __nccwpck_require__(2747) +const basename = __nccwpck_require__(692) +const getLimit = __nccwpck_require__(2393) + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "email", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "emoji", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "uuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "nanoid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid2", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ulid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "regex", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "duration", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ip", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "jwt", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cidr", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "base64", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "base64url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodError_1.ZodIssueCode.invalid_string, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil_1.errorUtil.errToObj(message) }); - } - base64url(message) { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return this._addCheck({ - kind: "base64url", - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil_1.errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil_1.errorUtil.errToObj(options) }); - } - datetime(options) { - var _a, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil_1.errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil_1.errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -exports.ZodString = ZodString; -ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); -} -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.number, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util_1.util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } + + onEnd = function () { + curFile = undefined + file.push(null) } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil_1.errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil_1.errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); - } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() } - return Number.isFinite(min) && Number.isFinite(max); + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart + + +/***/ }), + +/***/ 855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Decoder = __nccwpck_require__(1496) +const decodeText = __nccwpck_require__(2747) +const getLimit = __nccwpck_require__(2393) + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false } -exports.ZodNumber = ZodNumber; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } - catch (_a) { - return this._getInvalidInput(input); - } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.bigint) { - return this._getInvalidInput(input); + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.bigint, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true } - return max; + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } } + } + cb() } -exports.ZodBigInt = ZodBigInt; -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.boolean, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded + + +/***/ }), + +/***/ 1496: +/***/ ((module) => { + + + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined } - return (0, parseUtil_1.OK)(input.data); + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res } -exports.ZodBoolean = ZodBoolean; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.date, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_date, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder + + +/***/ }), + +/***/ 692: +/***/ ((module) => { + + + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); + } + return (path === '..' || path === '.' ? '' : path) +} + + +/***/ }), + +/***/ 2747: +/***/ (function(module) { + + + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; + if (typeof data === 'string') { + return data } -} -exports.ZodDate = ZodDate; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); -}; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.symbol, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } -} -exports.ZodSymbol = ZodSymbol; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.undefined, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } -} -exports.ZodUndefined = ZodUndefined; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); -}; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.null, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } -} -exports.ZodNull = ZodNull; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' } -} -exports.ZodAny = ZodAny; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); -}; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} } + return typeof data === 'string' + ? data + : data.toString() + } } -exports.ZodUnknown = ZodUnknown; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.never, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text } -exports.ZodNever = ZodNever; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.void, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; + +module.exports = decodeText + + +/***/ }), + +/***/ 2393: +/***/ ((module) => { + + + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} + + +/***/ }), + +/***/ 8929: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* eslint-disable object-property-newline */ + + +const decodeText = __nccwpck_require__(2747) + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') } - return (0, parseUtil_1.OK)(input.data); + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res } -exports.ZodVoid = ZodVoid; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); + +module.exports = parseParams + + +/***/ }), + +/***/ 2046: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __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); }; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const index_js_1 = __importDefault(__nccwpck_require__(1059)); +__exportStar(__nccwpck_require__(1059), exports); +exports["default"] = index_js_1.default; + + +/***/ }), + +/***/ 2111: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; +const util_js_1 = __nccwpck_require__(3304); +exports.ZodIssueCode = util_js_1.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +exports.quotelessJson = quotelessJson; +class ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } + else { + this.__proto__ = actualProto; } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return parseUtil_1.ParseStatus.mergeArray(status, result); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return parseUtil_1.ParseStatus.mergeArray(status, result); } - get element() { - return this._def.type; + toString() { + return this.message; } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, - }); + get message() { + return JSON.stringify(this.issues, util_js_1.util.jsonStringifyReplacer, 2); } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, - }); + get isEmpty() { + return this.issues.length === 0; } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, - }); + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; } - nonempty(message) { - return this.min(1, message); + get formErrors() { + return this.flatten(); } } -exports.ZodArray = ZodArray; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); +exports.ZodError = ZodError; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; }; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } + + +/***/ }), + +/***/ 7665: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.defaultErrorMap = void 0; +exports.setErrorMap = setErrorMap; +exports.getErrorMap = getErrorMap; +const en_js_1 = __importDefault(__nccwpck_require__(2929)); +exports.defaultErrorMap = en_js_1.default; +let overrideErrorMap = en_js_1.default; +function setErrorMap(map) { + overrideErrorMap = map; } -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; +function getErrorMap() { + return overrideErrorMap; +} + + +/***/ }), + +/***/ 8101: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util_1.util.objectKeys(shape); - return (this._cached = { shape, keys }); + 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 })); +__exportStar(__nccwpck_require__(7665), exports); +__exportStar(__nccwpck_require__(937), exports); +__exportStar(__nccwpck_require__(6822), exports); +__exportStar(__nccwpck_require__(3304), exports); +__exportStar(__nccwpck_require__(4741), exports); +__exportStar(__nccwpck_require__(2111), exports); + + +/***/ }), + +/***/ 1344: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.errorUtil = void 0; +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (exports.errorUtil = errorUtil = {})); + + +/***/ }), + +/***/ 937: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0; +exports.addIssueToContext = addIssueToContext; +const errors_js_1 = __nccwpck_require__(7665); +const en_js_1 = __importDefault(__nccwpck_require__(2929)); +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; +exports.makeIssue = makeIssue; +exports.EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = (0, errors_js_1.getErrorMap)(); + const issue = (0, exports.makeIssue)({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === en_js_1.default ? undefined : en_js_1.default, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return exports.INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, }); - return parseUtil_1.INVALID; } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return exports.INVALID; + if (value.status === "aborted") + return exports.INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; } } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); + return { status: status.value, value: finalObject }; + } +} +exports.ParseStatus = ParseStatus; +exports.INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +exports.DIRTY = DIRTY; +const OK = (value) => ({ status: "valid", value }); +exports.OK = OK; +const isAborted = (x) => x.status === "aborted"; +exports.isAborted = isAborted; +const isDirty = (x) => x.status === "dirty"; +exports.isDirty = isDirty; +const isValid = (x) => x.status === "valid"; +exports.isValid = isValid; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +exports.isAsync = isAsync; + + +/***/ }), + +/***/ 6822: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + + +/***/ }), + +/***/ 3304: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; +var util; +(function (util) { + util.assertEqual = (_) => { }; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); } } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (exports.util = util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (exports.objectUtil = objectUtil = {})); +exports.ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return exports.ZodParsedType.undefined; + case "string": + return exports.ZodParsedType.string; + case "number": + return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; + case "boolean": + return exports.ZodParsedType.boolean; + case "function": + return exports.ZodParsedType.function; + case "bigint": + return exports.ZodParsedType.bigint; + case "symbol": + return exports.ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return exports.ZodParsedType.array; } - else if (unknownKeys === "strip") { + if (data === null) { + return exports.ZodParsedType.null; } - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return exports.ZodParsedType.promise; } - } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); + if (typeof Map !== "undefined" && data instanceof Map) { + return exports.ZodParsedType.map; } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } + if (typeof Set !== "undefined" && data instanceof Set) { + return exports.ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return exports.ZodParsedType.date; + } + return exports.ZodParsedType.object; + default: + return exports.ZodParsedType.unknown; } - get shape() { - return this._def.shape(); +}; +exports.getParsedType = getParsedType; + + +/***/ }), + +/***/ 1059: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; } - strict(message) { - errorUtil_1.errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, + 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 __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 })); +exports.z = void 0; +const z = __importStar(__nccwpck_require__(8101)); +exports.z = z; +__exportStar(__nccwpck_require__(8101), exports); +exports["default"] = z; + + +/***/ }), + +/***/ 2929: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const ZodError_js_1 = __nccwpck_require__(2111); +const util_js_1 = __nccwpck_require__(3304); +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodError_js_1.ZodIssueCode.invalid_type: + if (issue.received === util_js_1.ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodError_js_1.ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`; + break; + case ZodError_js_1.ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_js_1.ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodError_js_1.ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodError_js_1.ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodError_js_1.ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util_js_1.util.assertNever(issue.validation); } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - util_1.util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - omit(mask) { - const shape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; } else { - newShape[key] = fieldSchema.optional(); + message = "Invalid"; } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); + break; + case ZodError_js_1.ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodError_js_1.ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_js_1.ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_js_1.util.assertNever(issue); } - required(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; + return { message }; +}; +exports["default"] = errorMap; + + +/***/ }), + +/***/ 4741: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; +exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = void 0; +exports.datetimeRegex = datetimeRegex; +exports.custom = custom; +const ZodError_js_1 = __nccwpck_require__(2111); +const errors_js_1 = __nccwpck_require__(7665); +const errorUtil_js_1 = __nccwpck_require__(1344); +const parseUtil_js_1 = __nccwpck_require__(937); +const util_js_1 = __nccwpck_require__(3304); +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; + this._cachedPath.push(...this._path, this._key); } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util_1.util.objectKeys(this.shape)); + } + return this._cachedPath; } } -exports.ZodObject = ZodObject; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - // return invalid - const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); - } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } +const handleResult = (ctx, result) => { + if ((0, parseUtil_js_1.isValid)(result)) { + return { success: true, data: result.value }; } - get options() { - return this._def.options; + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError_js_1.ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; } -} -exports.ZodUnion = ZodUnion; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); }; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + get description() { + return this._def.description; } - else if (type instanceof ZodLiteral) { - return [type.value]; + _getType(input) { + return (0, util_js_1.getParsedType)(input.data); } - else if (type instanceof ZodEnum) { - return type.options; + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util_1.util.objectValues(type.enum); + _processInputParams(input) { + return { + status: new parseUtil_js_1.ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); + _parseSync(input) { + const result = this._parse(input); + if ((0, parseUtil_js_1.isAsync)(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; } - else if (type instanceof ZodUndefined) { - return [undefined]; + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); } - else if (type instanceof ZodNull) { - return [null]; + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data), + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return (0, parseUtil_js_1.isValid)(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } + catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true, + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_js_1.isValid)(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }); } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } - else { - return []; - } -}; -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodError_js_1.ZodIssueCode.custom, + ...getIssueProperties(val), }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); + if (!result) { + setError(); + return false; + } + else { + return true; } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), }); } -} -exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; -function mergeValues(a, b) { - const aType = (0, util_1.getParsedType)(a); - const bType = (0, util_1.getParsedType)(b); - if (a === b) { - return { valid: true, data: a }; - } - else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { - const bKeys = util_1.util.objectKeys(b); - const sharedKeys = util_1.util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; + else { + return true; } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; + }); } - else if (aType === util_1.ZodParsedType.date && - bType === util_1.ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); } - else { - return { valid: false }; + superRefine(refinement) { + return this._refinement(refinement); } -} -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { - return parseUtil_1.INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_intersection_types, - }); - return parseUtil_1.INVALID; - } - if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } - } -} -exports.ZodIntersection = ZodIntersection; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); -}; -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (ctx.data.length < this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return parseUtil_1.INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return parseUtil_1.ParseStatus.mergeArray(status, results); - }); - } - else { - return parseUtil_1.ParseStatus.mergeArray(status, items); - } } - get items() { - return this._def.items; + optional() { + return ZodOptional.create(this, this._def); } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); + nullable() { + return ZodNullable.create(this, this._def); } -} -exports.ZodTuple = ZodTuple; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + nullish() { + return this.nullable().optional(); } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); -}; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; + array() { + return ZodArray.create(this); } - get valueSchema() { - return this._def.valueType; + promise() { + return ZodPromise.create(this, this._def); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (ctx.common.async) { - return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } + or(option) { + return ZodUnion.create([this, option], this._def); } - get element() { - return this._def.valueType; + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, }); } -} -exports.ZodRecord = ZodRecord; -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.map) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.map, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } } -} -exports.ZodMap = ZodMap; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); -}; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.set) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.set, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return parseUtil_1.INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, }); } - max(maxSize, message) { - return new ZodSet({ + describe(description) { + const This = this.constructor; + return new This({ ...this._def, - maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, + description, }); } - size(size, message) { - return this.min(size, message).max(size, message); + pipe(target) { + return ZodPipeline.create(this, target); } - nonempty(message) { - return this.min(1, message); + readonly() { + return ZodReadonly.create(this); } -} -exports.ZodSet = ZodSet; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); -}; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; + isOptional() { + return this.safeParse(undefined).success; } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.function) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.function, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - function makeArgsIssue(args, error) { - return (0, parseUtil_1.makeIssue)({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return (0, parseUtil_1.makeIssue)({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(async function (...args) { - const error = new ZodError_1.ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); + isNullable() { + return this.safeParse(null).success; } } -exports.ZodFunction = ZodFunction; -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); +exports.ZodType = ZodType; +exports.Schema = ZodType; +exports.ZodSchema = ZodType; +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +// faster, simpler, safer +const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } -exports.ZodLazy = ZodLazy; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); } -exports.ZodLiteral = ZodLiteral; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); +// Adapted from https://stackoverflow.com/a/3143231 +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); } -class ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); - } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, - }); + catch { + return false; } } -exports.ZodEnum = ZodEnum; -_ZodEnum_cache = new WeakMap(); -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== util_1.ZodParsedType.string && - ctx.parsedType !== util_1.ZodParsedType.number) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util_1.util.getValidEnumValues(this._def.values)), "f"); - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; } - get enum() { - return this._def.values; + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; } + return false; } -exports.ZodNativeEnum = ZodNativeEnum; -_ZodNativeEnum_cache = new WeakMap(); -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } +class ZodString extends ZodType { _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.promise && - ctx.common.async === false) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.promise, + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.string, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - const promisified = ctx.parsedType === util_1.ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return (0, parseUtil_1.OK)(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } -} -exports.ZodPromise = ZodPromise; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - (0, parseUtil_1.addIssueToContext)(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { + const status = new parseUtil_js_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); status.dirty(); } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; - }); + status.dirty(); + } } - else { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "email", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "emoji", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; + } } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "uuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, }); - }); + status.dirty(); + } } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!(0, parseUtil_1.isValid)(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "nanoid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); } - return { status: status.value, value: result }; } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!(0, parseUtil_1.isValid)(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid2", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ulid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + new URL(input.data); + } + catch { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "regex", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "duration", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ip", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "jwt", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cidr", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util_js_1.util.assertNever(check); } } - util_1.util.assertNever(effect); - } -} -exports.ZodEffects = ZodEffects; -exports.ZodTransformer = ZodEffects; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.undefined) { - return (0, parseUtil_1.OK)(undefined); - } - return this._def.innerType._parse(input); + return { status: status.value, value: input.data }; } - unwrap() { - return this._def.innerType; + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodError_js_1.ZodIssueCode.invalid_string, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); } -} -exports.ZodOptional = ZodOptional; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.null) { - return (0, parseUtil_1.OK)(null); - } - return this._def.innerType._parse(input); + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); } - unwrap() { - return this._def.innerType; + email(message) { + return this._addCheck({ kind: "email", ...errorUtil_js_1.errorUtil.errToObj(message) }); } -} -exports.ZodNullable = ZodNullable; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === util_1.ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, + url(message) { + return this._addCheck({ kind: "url", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64url(message) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil_js_1.errorUtil.errToObj(message), }); } - removeDefault() { - return this._def.innerType; + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil_js_1.errorUtil.errToObj(options) }); } -} -exports.ZodDefault = ZodDefault; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil_js_1.errorUtil.errToObj(options?.message), }); - if ((0, parseUtil_1.isAsync)(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, }); } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil_js_1.errorUtil.errToObj(options?.message), + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil_js_1.errorUtil.errToObj(options?.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_js_1.errorUtil.errToObj(message), + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil_js_1.errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } } + return min; } - removeCatch() { - return this._def.innerType; + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } } -exports.ZodCatch = ZodCatch; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, +exports.ZodString = ZodString; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, ...processCreateParams(params), }); }; -class ZodNaN extends ZodType { +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.nan) { + if (parsedType !== util_js_1.ZodParsedType.number) { const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.nan, + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.number, received: ctx.parsedType, }); - return parseUtil_1.INVALID; + return parseUtil_js_1.INVALID; } - return { status: "valid", value: input.data }; - } -} -exports.ZodNaN = ZodNaN; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -exports.BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, + let ctx = undefined; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_js_1.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message), + }, + ], }); } - unwrap() { - return this._def.type; + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_js_1.util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); } } -exports.ZodBranded = ZodBranded; -class ZodPipeline extends ZodType { +exports.ZodNumber = ZodNumber; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } + catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); status.dirty(); - return (0, parseUtil_1.DIRTY)(inResult.value); } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); + util_js_1.util.assertNever(check); } } + return { status: status.value, value: input.data }; } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.bigint, + received: ctx.parsedType, }); + return parseUtil_js_1.INVALID; } -} -exports.ZodPipeline = ZodPipeline; -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if ((0, parseUtil_1.isValid)(data)) { - data.value = Object.freeze(data.value); + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; } - return data; - }; - return (0, parseUtil_1.isAsync)(result) - ? result.then((data) => freeze(data)) - : freeze(result); + } + return min; } - unwrap() { - return this._def.innerType; + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; } } -exports.ZodReadonly = ZodReadonly; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, +exports.ZodBigInt = ZodBigInt; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, ...processCreateParams(params), }); }; -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -function cleanParams(params, data) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.boolean, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } } -function custom(check, _params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - const r = check(data); - if (r instanceof Promise) { - return r.then((r) => { - var _a, _b; - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); +exports.ZodBoolean = ZodBoolean; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.date, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_date, + }); + return parseUtil_js_1.INVALID; + } + const status = new parseUtil_js_1.ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } } - return; + else { + util_js_1.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], }); - return ZodAny.create(); -} -exports.custom = custom; -exports.late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {})); -// requires TS 4.4+ -class Class { - constructor(..._) { } + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } } -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -exports["instanceof"] = instanceOfType; -const stringType = ZodString.create; -exports.string = stringType; -const numberType = ZodNumber.create; -exports.number = numberType; -const nanType = ZodNaN.create; -exports.nan = nanType; -const bigIntType = ZodBigInt.create; -exports.bigint = bigIntType; -const booleanType = ZodBoolean.create; -exports.boolean = booleanType; -const dateType = ZodDate.create; -exports.date = dateType; -const symbolType = ZodSymbol.create; -exports.symbol = symbolType; -const undefinedType = ZodUndefined.create; -exports.undefined = undefinedType; -const nullType = ZodNull.create; -exports["null"] = nullType; -const anyType = ZodAny.create; -exports.any = anyType; -const unknownType = ZodUnknown.create; -exports.unknown = unknownType; -const neverType = ZodNever.create; -exports.never = neverType; -const voidType = ZodVoid.create; -exports["void"] = voidType; -const arrayType = ZodArray.create; -exports.array = arrayType; -const objectType = ZodObject.create; -exports.object = objectType; -const strictObjectType = ZodObject.strictCreate; -exports.strictObject = strictObjectType; -const unionType = ZodUnion.create; -exports.union = unionType; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -exports.discriminatedUnion = discriminatedUnionType; -const intersectionType = ZodIntersection.create; -exports.intersection = intersectionType; -const tupleType = ZodTuple.create; -exports.tuple = tupleType; -const recordType = ZodRecord.create; -exports.record = recordType; -const mapType = ZodMap.create; -exports.map = mapType; -const setType = ZodSet.create; -exports.set = setType; -const functionType = ZodFunction.create; -exports["function"] = functionType; -const lazyType = ZodLazy.create; -exports.lazy = lazyType; -const literalType = ZodLiteral.create; -exports.literal = literalType; -const enumType = ZodEnum.create; -exports["enum"] = enumType; -const nativeEnumType = ZodNativeEnum.create; -exports.nativeEnum = nativeEnumType; -const promiseType = ZodPromise.create; -exports.promise = promiseType; -const effectsType = ZodEffects.create; -exports.effect = effectsType; -exports.transformer = effectsType; -const optionalType = ZodOptional.create; -exports.optional = optionalType; -const nullableType = ZodNullable.create; -exports.nullable = nullableType; -const preprocessType = ZodEffects.createWithPreprocess; -exports.preprocess = preprocessType; -const pipelineType = ZodPipeline.create; -exports.pipeline = pipelineType; -const ostring = () => stringType().optional(); -exports.ostring = ostring; -const onumber = () => numberType().optional(); -exports.onumber = onumber; -const oboolean = () => booleanType().optional(); -exports.oboolean = oboolean; -exports.coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +exports.ZodDate = ZodDate; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); }; -exports.NEVER = parseUtil_1.INVALID; - - -/***/ }), - -/***/ 2078: -/***/ ((module) => { - -module.exports = eval("require")("encoding"); - - -/***/ }), - -/***/ 2613: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); - -/***/ }), - -/***/ 290: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); - -/***/ }), - -/***/ 181: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); - -/***/ }), - -/***/ 5317: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); - -/***/ }), - -/***/ 4236: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); - -/***/ }), - -/***/ 6982: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); - -/***/ }), - -/***/ 1637: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); - -/***/ }), - -/***/ 4434: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); - -/***/ }), - -/***/ 9896: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); - -/***/ }), - -/***/ 8611: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); - -/***/ }), - -/***/ 5675: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); - -/***/ }), - -/***/ 5692: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); - -/***/ }), - -/***/ 9278: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); - -/***/ }), - -/***/ 7598: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); - -/***/ }), - -/***/ 8474: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); - -/***/ }), - -/***/ 7075: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); - -/***/ }), - -/***/ 7975: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); - -/***/ }), - -/***/ 857: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); - -/***/ }), - -/***/ 6928: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); - -/***/ }), - -/***/ 2987: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); - -/***/ }), - -/***/ 4876: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("punycode"); - -/***/ }), - -/***/ 3480: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); - -/***/ }), - -/***/ 2203: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); - -/***/ }), - -/***/ 3774: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); - -/***/ }), - -/***/ 3193: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); - -/***/ }), - -/***/ 3557: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); - -/***/ }), - -/***/ 4756: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); - -/***/ }), - -/***/ 7016: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); - -/***/ }), - -/***/ 9023: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); - -/***/ }), - -/***/ 8253: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); - -/***/ }), - -/***/ 8167: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); - -/***/ }), - -/***/ 3106: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); - -/***/ }), - -/***/ 7182: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const inherits = (__nccwpck_require__(7975).inherits) - -const StreamSearch = __nccwpck_require__(4136) - -const PartStream = __nccwpck_require__(612) -const HeaderParser = __nccwpck_require__(2271) - -const DASH = 45 -const B_ONEDASH = Buffer.from('-') -const B_CRLF = Buffer.from('\r\n') -const EMPTY_FN = function () {} - -function Dicer (cfg) { - if (!(this instanceof Dicer)) { return new Dicer(cfg) } - WritableStream.call(this, cfg) - - if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - - if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - - this._headerFirst = cfg.headerFirst - - this._dashes = 0 - this._parts = 0 - this._finished = false - this._realFinish = false - this._isPreamble = true - this._justMatched = false - this._firstWrite = true - this._inHeader = true - this._part = undefined - this._cb = undefined - this._ignoreData = false - this._partOpts = { highWaterMark: cfg.partHwm } - this._pause = false - - const self = this - this._hparser = new HeaderParser(cfg) - this._hparser.on('header', function (header) { - self._inHeader = false - self._part.emit('header', header) - }) +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.symbol, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } } -inherits(Dicer, WritableStream) - -Dicer.prototype.emit = function (ev) { - if (ev === 'finish' && !this._realFinish) { - if (!this._finished) { - const self = this - process.nextTick(function () { - self.emit('error', new Error('Unexpected end of multipart data')) - if (self._part && !self._ignoreData) { - const type = (self._isPreamble ? 'Preamble' : 'Part') - self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) - self._part.push(null) - process.nextTick(function () { - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - return +exports.ZodSymbol = ZodSymbol; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.undefined, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodUndefined = ZodUndefined; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.null, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodNull = ZodNull; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodAny = ZodAny; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodUnknown = ZodUnknown; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.never, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } +} +exports.ZodNever = ZodNever; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.void, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } +} +exports.ZodVoid = ZodVoid; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return parseUtil_js_1.ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +exports.ZodArray = ZodArray; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util_js_1.util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); } - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) } - } else { WritableStream.prototype.emit.apply(this, arguments) } -} - -Dicer.prototype._write = function (data, encoding, cb) { - // ignore unexpected data (e.g. extra trailer data after finished) - if (!this._hparser && !this._bparser) { return cb() } - - if (this._headerFirst && this._isPreamble) { - if (!this._part) { - this._part = new PartStream(this._partOpts) - if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + get shape() { + return this._def.shape(); } - const r = this._hparser.push(data) - if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } - } - - // allows for "easier" testing - if (this._firstWrite) { - this._bparser.push(B_CRLF) - this._firstWrite = false - } - - this._bparser.push(data) - - if (this._pause) { this._cb = cb } else { cb() } -} - -Dicer.prototype.reset = function () { - this._part = undefined - this._bparser = undefined - this._hparser = undefined -} - -Dicer.prototype.setBoundary = function (boundary) { - const self = this - this._bparser = new StreamSearch('\r\n--' + boundary) - this._bparser.on('info', function (isMatch, data, start, end) { - self._oninfo(isMatch, data, start, end) - }) -} - -Dicer.prototype._ignore = function () { - if (this._part && !this._ignoreData) { - this._ignoreData = true - this._part.on('error', EMPTY_FN) - // we must perform some kind of read on the stream even though we are - // ignoring the data, otherwise node's Readable stream will not emit 'end' - // after pushing null to the stream - this._part.resume() - } -} - -Dicer.prototype._oninfo = function (isMatch, data, start, end) { - let buf; const self = this; let i = 0; let r; let shouldWriteMore = true - - if (!this._part && this._justMatched && data) { - while (this._dashes < 2 && (start + i) < end) { - if (data[start + i] === DASH) { - ++i - ++this._dashes - } else { - if (this._dashes) { buf = B_ONEDASH } - this._dashes = 0 - break - } + strict(message) { + errorUtil_js_1.errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); } - if (this._dashes === 2) { - if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } - this.reset() - this._finished = true - // no more parts will be added - if (self._parts === 0) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); } - if (this._dashes) { return } - } - if (this._justMatched) { this._justMatched = false } - if (!this._part) { - this._part = new PartStream(this._partOpts) - this._part._read = function (n) { - self._unpause() + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); } - if (this._isPreamble && this.listenerCount('preamble') !== 0) { - this.emit('preamble', this._part) - } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { - this.emit('part', this._part) - } else { - this._ignore() + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); } - if (!this._isPreamble) { this._inHeader = true } - } - if (data && start < end && !this._ignoreData) { - if (this._isPreamble || !this._inHeader) { - if (buf) { shouldWriteMore = this._part.push(buf) } - shouldWriteMore = this._part.push(data.slice(start, end)) - if (!shouldWriteMore) { this._pause = true } - } else if (!this._isPreamble && this._inHeader) { - if (buf) { this._hparser.push(buf) } - r = this._hparser.push(data.slice(start, end)) - if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; } - } - if (isMatch) { - this._hparser.reset() - if (this._isPreamble) { this._isPreamble = false } else { - if (start !== end) { - ++this._parts - this._part.on('end', function () { - if (--self._parts === 0) { - if (self._finished) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } else { - self._unpause() + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; } - } - }) - } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); } - this._part.push(null) - this._part = undefined - this._ignoreData = false - this._justMatched = true - this._dashes = 0 - } -} - -Dicer.prototype._unpause = function () { - if (!this._pause) { return } - - this._pause = false - if (this._cb) { - const cb = this._cb - this._cb = undefined - cb() - } -} - -module.exports = Dicer - - -/***/ }), - -/***/ 2271: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) -const getLimit = __nccwpck_require__(2393) - -const StreamSearch = __nccwpck_require__(4136) - -const B_DCRLF = Buffer.from('\r\n\r\n') -const RE_CRLF = /\r\n/g -const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex - -function HeaderParser (cfg) { - EventEmitter.call(this) - - cfg = cfg || {} - const self = this - this.nread = 0 - this.maxed = false - this.npairs = 0 - this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) - this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) - this.buffer = '' - this.header = {} - this.finished = false - this.ss = new StreamSearch(B_DCRLF) - this.ss.on('info', function (isMatch, data, start, end) { - if (data && !self.maxed) { - if (self.nread + end - start >= self.maxHeaderSize) { - end = self.maxHeaderSize - self.nread + start - self.nread = self.maxHeaderSize - self.maxed = true - } else { self.nread += (end - start) } - - self.buffer += data.toString('binary', start, end) + omit(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util_js_1.util.objectKeys(this.shape)); } - if (isMatch) { self._finish() } - }) -} -inherits(HeaderParser, EventEmitter) - -HeaderParser.prototype.push = function (data) { - const r = this.ss.push(data) - if (this.finished) { return r } -} - -HeaderParser.prototype.reset = function () { - this.finished = false - this.buffer = '' - this.header = {} - this.ss.reset() -} - -HeaderParser.prototype._finish = function () { - if (this.buffer) { this._parseHeader() } - this.ss.matches = this.ss.maxMatches - const header = this.header - this.header = {} - this.buffer = '' - this.finished = true - this.nread = this.npairs = 0 - this.maxed = false - this.emit('header', header) } - -HeaderParser.prototype._parseHeader = function () { - if (this.npairs === this.maxHeaderPairs) { return } - - const lines = this.buffer.split(RE_CRLF) - const len = lines.length - let m, h - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (lines[i].length === 0) { continue } - if (lines[i][0] === '\t' || lines[i][0] === ' ') { - // folded header content - // RFC2822 says to just remove the CRLF and not the whitespace following - // it, so we follow the RFC and include the leading whitespace ... - if (h) { - this.header[h][this.header[h].length - 1] += lines[i] - continue - } +exports.ZodObject = ZodObject; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError_js_1.ZodError(result.ctx.common.issues)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_js_1.INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError_js_1.ZodError(issues)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors, + }); + return parseUtil_js_1.INVALID; + } } - - const posColon = lines[i].indexOf(':') - if ( - posColon === -1 || - posColon === 0 - ) { - return + get options() { + return this._def.options; } - m = RE_HDR.exec(lines[i]) - h = m[1].toLowerCase() - this.header[h] = this.header[h] || [] - this.header[h].push((m[2] || '')) - if (++this.npairs === this.maxHeaderPairs) { break } - } -} - -module.exports = HeaderParser - - -/***/ }), - -/***/ 612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const inherits = (__nccwpck_require__(7975).inherits) -const ReadableStream = (__nccwpck_require__(7075).Readable) - -function PartStream (opts) { - ReadableStream.call(this, opts) -} -inherits(PartStream, ReadableStream) - -PartStream.prototype._read = function (n) {} - -module.exports = PartStream - - -/***/ }), - -/***/ 4136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -/** - * Copyright Brian White. All rights reserved. - * - * @see https://github.com/mscdex/streamsearch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation - * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool - */ -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) - -function SBMH (needle) { - if (typeof needle === 'string') { - needle = Buffer.from(needle) - } - - if (!Buffer.isBuffer(needle)) { - throw new TypeError('The needle has to be a String or a Buffer.') - } - - const needleLength = needle.length - - if (needleLength === 0) { - throw new Error('The needle cannot be an empty String/Buffer.') - } - - if (needleLength > 256) { - throw new Error('The needle cannot have a length bigger than 256.') - } - - this.maxMatches = Infinity - this.matches = 0 - - this._occ = new Array(256) - .fill(needleLength) // Initialize occurrence table. - this._lookbehind_size = 0 - this._needle = needle - this._bufpos = 0 - - this._lookbehind = Buffer.alloc(needleLength) - - // Populate occurrence table with analysis of the needle, - // ignoring last letter. - for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var - this._occ[needle[i]] = needleLength - 1 - i - } -} -inherits(SBMH, EventEmitter) - -SBMH.prototype.reset = function () { - this._lookbehind_size = 0 - this.matches = 0 - this._bufpos = 0 -} - -SBMH.prototype.push = function (chunk, pos) { - if (!Buffer.isBuffer(chunk)) { - chunk = Buffer.from(chunk, 'binary') - } - const chlen = chunk.length - this._bufpos = pos || 0 - let r - while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } - return r } - -SBMH.prototype._sbmh_feed = function (data) { - const len = data.length - const needle = this._needle - const needleLength = needle.length - const lastNeedleChar = needle[needleLength - 1] - - // Positive: points to a position in `data` - // pos == 3 points to data[3] - // Negative: points to a position in the lookbehind buffer - // pos == -2 points to lookbehind[lookbehind_size - 2] - let pos = -this._lookbehind_size - let ch - - if (pos < 0) { - // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool - // search with character lookup code that considers both the - // lookbehind buffer and the current round's haystack data. - // - // Loop until - // there is a match. - // or until - // we've moved past the position that requires the - // lookbehind buffer. In this case we switch to the - // optimized loop. - // or until - // the character to look at lies outside the haystack. - while (pos < 0 && pos <= len - needleLength) { - ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - - if ( - ch === lastNeedleChar && - this._sbmh_memcmp(data, pos, needleLength - 1) - ) { - this._lookbehind_size = 0 - ++this.matches - this.emit('info', true) - - return (this._bufpos = pos + needleLength) - } - pos += this._occ[ch] +exports.ZodUnion = ZodUnion; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); } - - // No match. - - if (pos < 0) { - // There's too few data for Boyer-Moore-Horspool to run, - // so let's use a different algorithm to skip as much as - // we can. - // Forward pos until - // the trailing part of lookbehind + data - // looks like the beginning of the needle - // or until - // pos == 0 - while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); } - - if (pos >= 0) { - // Discard lookbehind buffer. - this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) - this._lookbehind_size = 0 - } else { - // Cut off part of the lookbehind buffer that has - // been processed and append the entire haystack - // into it. - const bytesToCutOff = this._lookbehind_size + pos - if (bytesToCutOff > 0) { - // The cut off data is guaranteed not to contain the needle. - this.emit('info', false, this._lookbehind, 0, bytesToCutOff) - } - - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) - this._lookbehind_size -= bytesToCutOff - - data.copy(this._lookbehind, this._lookbehind_size) - this._lookbehind_size += len - - this._bufpos = len - return len + else if (type instanceof ZodLiteral) { + return [type.value]; } - } - - pos += (pos >= 0) * this._bufpos - - // Lookbehind buffer is now empty. We only need to check if the - // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) - ++this.matches - if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength - } - - // There was no match. If there's trailing haystack data that we cannot - // match yet using the Boyer-Moore-Horspool algorithm (because the trailing - // data is less than the needle size) then match using a modified - // algorithm that starts matching from the beginning instead of the end. - // Whatever trailing data is left after running this algorithm is added to - // the lookbehind buffer. - while ( - pos < len && - ( - data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) - ) - ) { - ++pos - } - if (pos < len) { - data.copy(this._lookbehind, 0, pos, pos + (len - pos)) - this._lookbehind_size = len - pos - } - - // Everything until pos is guaranteed not to contain needle data. - if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - - this._bufpos = len - return len -} - -SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) - ? this._lookbehind[this._lookbehind_size + pos] - : data[pos] -} - -SBMH.prototype._sbmh_memcmp = function (data, pos, len) { - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } - } - return true -} - -module.exports = SBMH - - -/***/ }), - -/***/ 9581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const { inherits } = __nccwpck_require__(7975) -const Dicer = __nccwpck_require__(7182) - -const MultipartParser = __nccwpck_require__(1192) -const UrlencodedParser = __nccwpck_require__(855) -const parseParams = __nccwpck_require__(8929) - -function Busboy (opts) { - if (!(this instanceof Busboy)) { return new Busboy(opts) } - - if (typeof opts !== 'object') { - throw new TypeError('Busboy expected an options-Object.') - } - if (typeof opts.headers !== 'object') { - throw new TypeError('Busboy expected an options-Object with headers-attribute.') - } - if (typeof opts.headers['content-type'] !== 'string') { - throw new TypeError('Missing Content-Type-header.') - } - - const { - headers, - ...streamOptions - } = opts - - this.opts = { - autoDestroy: false, - ...streamOptions - } - WritableStream.call(this, this.opts) - - this._done = false - this._parser = this.getParserByHeaders(headers) - this._finished = false -} -inherits(Busboy, WritableStream) - -Busboy.prototype.emit = function (ev) { - if (ev === 'finish') { - if (!this._done) { - this._parser?.end() - return - } else if (this._finished) { - return + else if (type instanceof ZodEnum) { + return type.options; } - this._finished = true - } - WritableStream.prototype.emit.apply(this, arguments) -} - -Busboy.prototype.getParserByHeaders = function (headers) { - const parsed = parseParams(headers['content-type']) - - const cfg = { - defCharset: this.opts.defCharset, - fileHwm: this.opts.fileHwm, - headers, - highWaterMark: this.opts.highWaterMark, - isPartAFile: this.opts.isPartAFile, - limits: this.opts.limits, - parsedConType: parsed, - preservePath: this.opts.preservePath - } - - if (MultipartParser.detect.test(parsed[0])) { - return new MultipartParser(this, cfg) - } - if (UrlencodedParser.detect.test(parsed[0])) { - return new UrlencodedParser(this, cfg) - } - throw new Error('Unsupported Content-Type.') -} - -Busboy.prototype._write = function (chunk, encoding, cb) { - this._parser.write(chunk, cb) -} - -module.exports = Busboy -module.exports["default"] = Busboy -module.exports.Busboy = Busboy - -module.exports.Dicer = Dicer - - -/***/ }), - -/***/ 1192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// TODO: -// * support 1 nested multipart level -// (see second multipart example here: -// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) -// * support limits.fieldNameSize -// -- this will require modifications to utils.parseParams - -const { Readable } = __nccwpck_require__(7075) -const { inherits } = __nccwpck_require__(7975) - -const Dicer = __nccwpck_require__(7182) - -const parseParams = __nccwpck_require__(8929) -const decodeText = __nccwpck_require__(2747) -const basename = __nccwpck_require__(692) -const getLimit = __nccwpck_require__(2393) - -const RE_BOUNDARY = /^boundary$/i -const RE_FIELD = /^form-data$/i -const RE_CHARSET = /^charset$/i -const RE_FILENAME = /^filename$/i -const RE_NAME = /^name$/i - -Multipart.detect = /^multipart\/form-data/i -function Multipart (boy, cfg) { - let i - let len - const self = this - let boundary - const limits = cfg.limits - const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) - const parsedConType = cfg.parsedConType || [] - const defCharset = cfg.defCharset || 'utf8' - const preservePath = cfg.preservePath - const fileOpts = { highWaterMark: cfg.fileHwm } - - for (i = 0, len = parsedConType.length; i < len; ++i) { - if (Array.isArray(parsedConType[i]) && - RE_BOUNDARY.test(parsedConType[i][0])) { - boundary = parsedConType[i][1] - break + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util_js_1.util.objectValues(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } +}; +class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return parseUtil_js_1.INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } } - } - - function checkFinished () { - if (nends === 0 && finished && !boy._done) { - finished = false - self.end() + get discriminator() { + return this._def.discriminator; } - } - - if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - - const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) - const filesLimit = getLimit(limits, 'files', Infinity) - const fieldsLimit = getLimit(limits, 'fields', Infinity) - const partsLimit = getLimit(limits, 'parts', Infinity) - const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) - const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) - - let nfiles = 0 - let nfields = 0 - let nends = 0 - let curFile - let curField - let finished = false - - this._needDrain = false - this._pause = false - this._cb = undefined - this._nparts = 0 - this._boy = boy - - const parserCfg = { - boundary, - maxHeaderPairs: headerPairsLimit, - maxHeaderSize: headerSizeLimit, - partHwm: fileOpts.highWaterMark, - highWaterMark: cfg.highWaterMark - } - - this.parser = new Dicer(parserCfg) - this.parser.on('drain', function () { - self._needDrain = false - if (self._cb && !self._pause) { - const cb = self._cb - self._cb = undefined - cb() + get options() { + return this._def.options; } - }).on('part', function onPart (part) { - if (++self._nparts > partsLimit) { - self.parser.removeListener('part', onPart) - self.parser.on('part', skipPart) - boy.hitPartsLimit = true - boy.emit('partsLimit') - return skipPart(part) + get optionsMap() { + return this._def.optionsMap; } - - // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let - // us emit 'end' early since we know the part has ended if we are already - // seeing the next part - if (curField) { - const field = curField - field.emit('end') - field.removeAllListeners('end') + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); } - - part.on('header', function (header) { - let contype - let fieldname - let parsed - let charset - let encoding - let filename - let nsize = 0 - - if (header['content-type']) { - parsed = parseParams(header['content-type'][0]) - if (parsed[0]) { - contype = parsed[0].toLowerCase() - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_CHARSET.test(parsed[i][0])) { - charset = parsed[i][1].toLowerCase() - break +} +exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; +function mergeValues(a, b) { + const aType = (0, util_js_1.getParsedType)(a); + const bType = (0, util_js_1.getParsedType)(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) { + const bKeys = util_js_1.util.objectKeys(b); + const sharedKeys = util_js_1.util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; } - } + newObj[key] = sharedValue.data; } - } - - if (contype === undefined) { contype = 'text/plain' } - if (charset === undefined) { charset = defCharset } - - if (header['content-disposition']) { - parsed = parseParams(header['content-disposition'][0]) - if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_NAME.test(parsed[i][0])) { - fieldname = parsed[i][1] - } else if (RE_FILENAME.test(parsed[i][0])) { - filename = parsed[i][1] - if (!preservePath) { filename = basename(filename) } - } + return { valid: true, data: newObj }; + } + else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; } - } else { return skipPart(part) } - - if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - - let onData, - onEnd - - if (isPartAFile(fieldname, contype, filename)) { - // file/binary field - if (nfiles === filesLimit) { - if (!boy.hitFilesLimit) { - boy.hitFilesLimit = true - boy.emit('filesLimit') - } - return skipPart(part) + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); } - - ++nfiles - - if (boy.listenerCount('file') === 0) { - self.parser._ignore() - return + return { valid: true, data: newArray }; + } + else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) { + return parseUtil_js_1.INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_intersection_types, + }); + return parseUtil_js_1.INVALID; + } + if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.isDirty)(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); } - - ++nends - const file = new FileStream(fileOpts) - curFile = file - file.on('end', function () { - --nends - self._pause = false - checkFinished() - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - }) - file._read = function (n) { - if (!self._pause) { return } - self._pause = false - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); } - boy.emit('file', fieldname, file, filename, encoding, contype) - - onData = function (data) { - if ((nsize += data.length) > fileSizeLimit) { - const extralen = fileSizeLimit - nsize + data.length - if (extralen > 0) { file.push(data.slice(0, extralen)) } - file.truncated = true - file.bytesRead = fileSizeLimit - part.removeAllListeners('data') - file.emit('limit') - return - } else if (!file.push(data)) { self._pause = true } - - file.bytesRead = nsize + } +} +exports.ZodIntersection = ZodIntersection; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } - - onEnd = function () { - curFile = undefined - file.push(null) + if (ctx.data.length < this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return parseUtil_js_1.INVALID; } - } else { - // non-file field - if (nfields === fieldsLimit) { - if (!boy.hitFieldsLimit) { - boy.hitFieldsLimit = true - boy.emit('fieldsLimit') - } - return skipPart(part) + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); } - - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part - - onData = function (data) { - if ((nsize += data.length) > fieldSizeLimit) { - const extralen = (fieldSizeLimit - (nsize - data.length)) - buffer += data.toString('binary', 0, extralen) - truncated = true - part.removeAllListeners('data') - } else { buffer += data.toString('binary') } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, results); + }); } - - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() + else { + return parseUtil_js_1.ParseStatus.mergeArray(status, items); } - } - - /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become - broken. Streams2/streams3 is a huge black box of confusion, but - somehow overriding the sync state seems to fix things again (and still - seems to work for previous node versions). - */ - part._readableState.sync = false - - part.on('data', onData) - part.on('end', onEnd) - }).on('error', function (err) { - if (curFile) { curFile.emit('error', err) } - }) - }).on('error', function (err) { - boy.emit('error', err) - }).on('finish', function () { - finished = true - checkFinished() - }) -} - -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb - } -} - -Multipart.prototype.end = function () { - const self = this - - if (self.parser.writable) { - self.parser.end() - } else if (!self._boy._done) { - process.nextTick(function () { - self._boy._done = true - self._boy.emit('finish') - }) - } -} - -function skipPart (part) { - part.resume() -} - -function FileStream (opts) { - Readable.call(this, opts) - - this.bytesRead = 0 - - this.truncated = false + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } } - -inherits(FileStream, Readable) - -FileStream.prototype._read = function (n) {} - -module.exports = Multipart - - -/***/ }), - -/***/ 855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Decoder = __nccwpck_require__(1496) -const decodeText = __nccwpck_require__(2747) -const getLimit = __nccwpck_require__(2393) - -const RE_CHARSET = /^charset$/i - -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy - - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) - - let charset - for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var - if (Array.isArray(parsedConType[i]) && - RE_CHARSET.test(parsedConType[i][0])) { - charset = parsedConType[i][1].toLowerCase() - break +exports.ZodTuple = ZodTuple; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); } - } - - if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - - this.decoder = new Decoder() - this.charset = charset - this._fields = 0 - this._state = 'key' - this._checkingBytes = true - this._bytesKey = 0 - this._bytesVal = 0 - this._key = '' - this._val = '' - this._keyTrunc = false - this._valTrunc = false - this._hitLimit = false } - -UrlEncoded.prototype.write = function (data, cb) { - if (this._fields === this.fieldsLimit) { - if (!this.boy.hitFieldsLimit) { - this.boy.hitFieldsLimit = true - this.boy.emit('fieldsLimit') +exports.ZodRecord = ZodRecord; +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; } - return cb() - } - - let idxeq; let idxamp; let i; let p = 0; const len = data.length - - while (p < len) { - if (this._state === 'key') { - idxeq = idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x3D/* = */) { - idxeq = i - break - } else if (data[i] === 0x26/* & */) { - idxamp = i - break + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.map) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.map, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } - if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesKey } - } - - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' - - this._hitLimit = false - this._checkingBytes = true - this._val = '' - this._bytesVal = 0 - this._valTrunc = false - this.decoder.reset() - - p = idxeq + 1 - } else if (idxamp !== undefined) { - // key with no assignment - ++this._fields - let key; const keyTrunc = this._keyTrunc - if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); } - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._keyTrunc = true + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; } - } else { - if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } - p = len - } - } else { - idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x26/* & */) { - idxamp = i - break + } +} +exports.ZodMap = ZodMap; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.set) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.set, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; } - if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesVal } - } - - if (idxamp !== undefined) { - ++this._fields - if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - this._state = 'key' - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._val === '' && this.fieldSizeLimit === 0) || - (this._bytesVal = this._val.length) === this.fieldSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._valTrunc = true + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return parseUtil_js_1.INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } } - } - cb() -} - -UrlEncoded.prototype.end = function () { - if (this.boy._done) { return } - - if (this._state === 'key' && this._key.length > 0) { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - '', - this._keyTrunc, - false) - } else if (this._state === 'val') { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - } - this.boy._done = true - this.boy.emit('finish') -} - -module.exports = UrlEncoded - - -/***/ }), - -/***/ 1496: -/***/ ((module) => { - - - -const RE_PLUS = /\+/g - -const HEX = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -] - -function Decoder () { - this.buffer = undefined + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil_js_1.errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } } -Decoder.prototype.write = function (str) { - // Replace '+' with ' ' before decoding - str = str.replace(RE_PLUS, ' ') - let res = '' - let i = 0; let p = 0; const len = str.length - for (; i < len; ++i) { - if (this.buffer !== undefined) { - if (!HEX[str.charCodeAt(i)]) { - res += '%' + this.buffer - this.buffer = undefined - --i // retry character - } else { - this.buffer += str[i] - ++p - if (this.buffer.length === 2) { - res += String.fromCharCode(parseInt(this.buffer, 16)) - this.buffer = undefined +exports.ZodSet = ZodSet; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.function) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.function, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + function makeArgsIssue(args, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x) => !!x), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return (0, parseUtil_js_1.OK)(async function (...args) { + const error = new ZodError_js_1.ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return (0, parseUtil_js_1.OK)(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError_js_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError_js_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); } - } - } else if (str[i] === '%') { - if (i > p) { - res += str.substring(p, i) - p = i - } - this.buffer = '' - ++p } - } - if (p < len && this.buffer === undefined) { res += str.substring(p) } - return res -} -Decoder.prototype.reset = function () { - this.buffer = undefined + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } } - -module.exports = Decoder - - -/***/ }), - -/***/ 692: -/***/ ((module) => { - - - -module.exports = function basename (path) { - if (typeof path !== 'string') { return '' } - for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var - switch (path.charCodeAt(i)) { - case 0x2F: // '/' - case 0x5C: // '\' - path = path.slice(i + 1) - return (path === '..' || path === '.' ? '' : path) +exports.ZodFunction = ZodFunction; +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } - } - return (path === '..' || path === '.' ? '' : path) } - - -/***/ }), - -/***/ 2747: -/***/ (function(module) { - - - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue +exports.ZodLazy = ZodLazy; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return parseUtil_js_1.INVALID; } - return decoders.other.bind(charset) + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; } - } } - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' +exports.ZodLiteral = ZodLiteral; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type, + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + get options() { + return this._def.values; } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - if (typeof data === 'string') { - return data + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - return data.latin1Slice(0, data.length) - }, - - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) +} +exports.ZodEnum = ZodEnum; +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type, + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' + get enum() { + return this._def.values; } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) +} +exports.ZodNativeEnum = ZodNativeEnum; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.promise, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return (0, parseUtil_js_1.OK)(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); } - return typeof data === 'string' - ? data - : data.toString() - } } - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text +exports.ZodPromise = ZodPromise; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + (0, parseUtil_js_1.addIssueToContext)(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + }); + } + else { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } + } + util_js_1.util.assertNever(effect); + } } - -module.exports = decodeText - - -/***/ }), - -/***/ 2393: -/***/ ((module) => { - - - -module.exports = function getLimit (limits, name, defaultLimit) { - if ( - !limits || - limits[name] === undefined || - limits[name] === null - ) { return defaultLimit } - - if ( - typeof limits[name] !== 'number' || - isNaN(limits[name]) - ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - - return limits[name] +exports.ZodEffects = ZodEffects; +exports.ZodTransformer = ZodEffects; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.undefined) { + return (0, parseUtil_js_1.OK)(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } } - - -/***/ }), - -/***/ 8929: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(2747) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +exports.ZodOptional = ZodOptional; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.null) { + return (0, parseUtil_js_1.OK)(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +exports.ZodNullable = ZodNullable; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === util_js_1.ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +exports.ZodDefault = ZodDefault; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if ((0, parseUtil_js_1.isAsync)(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } } - -function encodedReplacer (match) { - return EncodedLookup[match] +exports.ZodCatch = ZodCatch; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.nan, + received: ctx.parsedType, + }); + return parseUtil_js_1.INVALID; + } + return { status: "valid", value: input.data }; + } } - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') +exports.ZodNaN = ZodNaN; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +exports.BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +exports.ZodBranded = ZodBranded; +class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return (0, parseUtil_js_1.DIRTY)(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } } - -module.exports = parseParams +exports.ZodPipeline = ZodPipeline; +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if ((0, parseUtil_js_1.isValid)(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +} +exports.ZodReadonly = ZodReadonly; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +exports.late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +exports["instanceof"] = instanceOfType; +const stringType = ZodString.create; +exports.string = stringType; +const numberType = ZodNumber.create; +exports.number = numberType; +const nanType = ZodNaN.create; +exports.nan = nanType; +const bigIntType = ZodBigInt.create; +exports.bigint = bigIntType; +const booleanType = ZodBoolean.create; +exports.boolean = booleanType; +const dateType = ZodDate.create; +exports.date = dateType; +const symbolType = ZodSymbol.create; +exports.symbol = symbolType; +const undefinedType = ZodUndefined.create; +exports.undefined = undefinedType; +const nullType = ZodNull.create; +exports["null"] = nullType; +const anyType = ZodAny.create; +exports.any = anyType; +const unknownType = ZodUnknown.create; +exports.unknown = unknownType; +const neverType = ZodNever.create; +exports.never = neverType; +const voidType = ZodVoid.create; +exports["void"] = voidType; +const arrayType = ZodArray.create; +exports.array = arrayType; +const objectType = ZodObject.create; +exports.object = objectType; +const strictObjectType = ZodObject.strictCreate; +exports.strictObject = strictObjectType; +const unionType = ZodUnion.create; +exports.union = unionType; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +exports.discriminatedUnion = discriminatedUnionType; +const intersectionType = ZodIntersection.create; +exports.intersection = intersectionType; +const tupleType = ZodTuple.create; +exports.tuple = tupleType; +const recordType = ZodRecord.create; +exports.record = recordType; +const mapType = ZodMap.create; +exports.map = mapType; +const setType = ZodSet.create; +exports.set = setType; +const functionType = ZodFunction.create; +exports["function"] = functionType; +const lazyType = ZodLazy.create; +exports.lazy = lazyType; +const literalType = ZodLiteral.create; +exports.literal = literalType; +const enumType = ZodEnum.create; +exports["enum"] = enumType; +const nativeEnumType = ZodNativeEnum.create; +exports.nativeEnum = nativeEnumType; +const promiseType = ZodPromise.create; +exports.promise = promiseType; +const effectsType = ZodEffects.create; +exports.effect = effectsType; +exports.transformer = effectsType; +const optionalType = ZodOptional.create; +exports.optional = optionalType; +const nullableType = ZodNullable.create; +exports.nullable = nullableType; +const preprocessType = ZodEffects.createWithPreprocess; +exports.preprocess = preprocessType; +const pipelineType = ZodPipeline.create; +exports.pipeline = pipelineType; +const ostring = () => stringType().optional(); +exports.ostring = ostring; +const onumber = () => numberType().optional(); +exports.onumber = onumber; +const oboolean = () => booleanType().optional(); +exports.oboolean = oboolean; +exports.coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; +exports.NEVER = parseUtil_js_1.INVALID; /***/ }), @@ -68301,7 +68334,7 @@ __nccwpck_require__.d(src_core_namespaceObject, { }); // EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var core = __nccwpck_require__(7484); +var lib_core = __nccwpck_require__(7484); // EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js var github = __nccwpck_require__(3228); ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs @@ -76317,7 +76350,7 @@ const formatRequestDetails = (details) => { }; //# sourceMappingURL=log.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/version.mjs -const version_VERSION = '0.50.4'; // x-release-please-version +const version_VERSION = '0.54.0'; // x-release-please-version //# sourceMappingURL=version.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -76373,10 +76406,10 @@ const detect_platform_getPlatformProperties = () => { return { 'X-Stainless-Lang': 'js', 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform), - 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch), + 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch ?? 'unknown'), 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': globalThis.process.version, + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', }; } const browserInfo = detect_platform_getBrowserInfo(); @@ -76494,7 +76527,7 @@ function makeReadableStream(...args) { } return new ReadableStream(...args); } -function shims_ReadableStreamFrom(iterable) { +function ReadableStreamFrom(iterable) { let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); return makeReadableStream({ start() { }, @@ -77344,13 +77377,18 @@ const uploads_addFormValue = async (form, key, value) => { form.append(key, String(value)); } else if (value instanceof Response) { - form.append(key, makeFile([await value.blob()], uploads_getName(value))); + let options = {}; + const contentType = value.headers.get('Content-Type'); + if (contentType) { + options = { type: contentType }; + } + form.append(key, makeFile([await value.blob()], uploads_getName(value), options)); } else if (isAsyncIterable(value)) { form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], uploads_getName(value))); } else if (isNamedBlob(value)) { - form.append(key, value, uploads_getName(value)); + form.append(key, makeFile([value], uploads_getName(value), { type: value.type })); } else if (Array.isArray(value)) { await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); @@ -77401,12 +77439,18 @@ async function to_file_toFile(value, name, options) { checkFileSupport(); // If it's a promise, resolve it. value = await value; - // If we've been given a `File` we don't need to do anything + name || (name = uploads_getName(value)); + // If we've been given a `File` we don't need to do anything if the name / options + // have not been customised. if (to_file_isFileLike(value)) { - if (value instanceof File) { + if (value instanceof File && name == null && options == null) { return value; } - return makeFile([await value.arrayBuffer()], value.name); + return makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options, + }); } if (to_file_isResponseLike(value)) { const blob = await value.blob(); @@ -77414,7 +77458,6 @@ async function to_file_toFile(value, name, options) { return makeFile(await to_file_getBytes(blob), name, options); } const parts = await to_file_getBytes(value); - name || (name = uploads_getName(value)); if (!options?.type) { const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); if (typeof type === 'string') { @@ -77592,6 +77635,125 @@ const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(sta */ const path = createPathTagFunction(encodeURIPath); //# sourceMappingURL=path.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class beta_files_Files extends resource_APIResource { + /** + * List Files + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fileMetadata of client.beta.files.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/files', (pagination_Page), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete File + * + * @example + * ```ts + * const deletedFile = await client.beta.files.delete( + * 'file_id', + * ); + * ``` + */ + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Download File + * + * @example + * ```ts + * const response = await client.beta.files.download( + * 'file_id', + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` + */ + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/files/${fileID}/content`, { + ...options, + headers: buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + __binaryResponse: true, + }); + } + /** + * Get File Metadata + * + * @example + * ```ts + * const fileMetadata = + * await client.beta.files.retrieveMetadata('file_id'); + * ``` + */ + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Upload File + * + * @example + * ```ts + * const fileMetadata = await client.beta.files.upload({ + * file: fs.createReadStream('path/to/file'), + * }); + * ``` + */ + upload(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/files', uploads_multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }, this._client)); + } +} +//# sourceMappingURL=files.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/models.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -78124,6 +78286,9 @@ var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _Be const JSON_BUF_PROPERTY = '__json_buf'; +function tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use'; +} class BetaMessageStream { constructor() { _BetaMessageStream_instances.add(this); @@ -78469,7 +78634,7 @@ class BetaMessageStream { break; } case 'input_json_delta': { - if (content.type === 'tool_use' && content.input) { + if (tracksToolInput(content) && content.input) { this._emit('inputJson', event.delta.partial_json, content.input); } break; @@ -78533,6 +78698,7 @@ class BetaMessageStream { case 'message_stop': return snapshot; case 'message_delta': + snapshot.container = event.delta.container; snapshot.stop_reason = event.delta.stop_reason; snapshot.stop_sequence = event.delta.stop_sequence; snapshot.usage.output_tokens = event.usage.output_tokens; @@ -78569,7 +78735,7 @@ class BetaMessageStream { break; } case 'input_json_delta': { - if (snapshotContent?.type === 'tool_use') { + if (snapshotContent && tracksToolInput(snapshotContent)) { // we need to keep track of the raw JSON string as well so that we can // re-parse it for each delta, for now we just store it as an untyped // non-enumerable property on the snapshot @@ -78581,7 +78747,13 @@ class BetaMessageStream { writable: true, }); if (jsonBuf) { - snapshotContent.input = parser_partialParse(jsonBuf); + try { + snapshotContent.input = parser_partialParse(jsonBuf); + } + catch (err) { + const error = new error_AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + tslib_classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); + } } } break; @@ -78665,6 +78837,19 @@ class BetaMessageStream { // used to ensure exhaustive case matching without throwing a runtime error function checkNever(x) { } //# sourceMappingURL=BetaMessageStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/constants.mjs +// File containing shared constants +/** + * Model-specific timeout constraints for non-streaming requests + */ +const MODEL_NONSTREAMING_TOKENS = { + 'claude-opus-4-20250514': 8192, + 'claude-opus-4-0': 8192, + 'claude-4-opus-20250514': 8192, + 'anthropic.claude-opus-4-20250514-v1:0': 8192, + 'claude-opus-4@20250514': 8192, +}; +//# sourceMappingURL=constants.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -78682,6 +78867,7 @@ const DEPRECATED_MODELS = { 'claude-2.1': 'July 21st, 2025', 'claude-2.0': 'July 21st, 2025', }; + class messages_messages_Messages extends resource_APIResource { constructor() { super(...arguments); @@ -78692,10 +78878,14 @@ class messages_messages_Messages extends resource_APIResource { if (body.model in DEPRECATED_MODELS) { console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } return this._client.post('/v1/messages?beta=true', { body, - timeout: this._client._options.timeout ?? - (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)), + timeout: timeout ?? 600000, ...options, headers: buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, @@ -78749,15 +78939,19 @@ messages_messages_Messages.Batches = batches_Batches; + + class beta_Beta extends resource_APIResource { constructor() { super(...arguments); this.models = new models_Models(this._client); this.messages = new messages_messages_Messages(this._client); + this.files = new beta_files_Files(this._client); } } beta_Beta.Models = models_Models; beta_Beta.Messages = messages_messages_Messages; +beta_Beta.Files = beta_files_Files; //# sourceMappingURL=beta.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/completions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -78779,156 +78973,6 @@ class resources_completions_Completions extends resource_APIResource { } } //# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class messages_batches_Batches extends resource_APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-3-7-sonnet-20250219', - * }, - * }, - * ], - * }); - * ``` - */ - create(body, options) { - return this._client.post('/v1/messages/batches', { body, ...options }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, options) { - return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const messageBatch of client.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/v1/messages/batches', (pagination_Page), { query, ...options }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const deletedMessageBatch = - * await client.messages.batches.delete('message_batch_id'); - * ``` - */ - delete(messageBatchID, options) { - return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, options) { - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatchIndividualResponse = - * await client.messages.batches.results('message_batch_id'); - * ``` - */ - async results(messageBatchID, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - } - return this._client - .get(batch.results_url, { - ...options, - headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - stream: true, - __binaryResponse: true, - }) - ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -} -//# sourceMappingURL=batches.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; @@ -78937,6 +78981,9 @@ var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStr const MessageStream_JSON_BUF_PROPERTY = '__json_buf'; +function MessageStream_tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use'; +} class MessageStream { constructor() { _MessageStream_instances.add(this); @@ -79282,7 +79329,7 @@ class MessageStream { break; } case 'input_json_delta': { - if (content.type === 'tool_use' && content.input) { + if (MessageStream_tracksToolInput(content) && content.input) { this._emit('inputJson', event.delta.partial_json, content.input); } break; @@ -79383,7 +79430,7 @@ class MessageStream { break; } case 'input_json_delta': { - if (snapshotContent?.type === 'tool_use') { + if (snapshotContent && MessageStream_tracksToolInput(snapshotContent)) { // we need to keep track of the raw JSON string as well so that we can // re-parse it for each delta, for now we just store it as an untyped // non-enumerable property on the snapshot @@ -79479,6 +79526,156 @@ class MessageStream { // used to ensure exhaustive case matching without throwing a runtime error function MessageStream_checkNever(x) { } //# sourceMappingURL=MessageStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class messages_batches_Batches extends resource_APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-3-7-sonnet-20250219', + * }, + * }, + * ], + * }); + * ``` + */ + create(body, options) { + return this._client.post('/v1/messages/batches', { body, ...options }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, options) { + return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const messageBatch of client.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/v1/messages/batches', (pagination_Page), { query, ...options }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const deletedMessageBatch = + * await client.messages.batches.delete('message_batch_id'); + * ``` + */ + delete(messageBatchID, options) { + return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, options) { + return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatchIndividualResponse = + * await client.messages.batches.results('message_batch_id'); + * ``` + */ + async results(messageBatchID, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +} +//# sourceMappingURL=batches.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -79495,10 +79692,14 @@ class resources_messages_messages_Messages extends resource_APIResource { if (body.model in messages_DEPRECATED_MODELS) { console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${messages_DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } return this._client.post('/v1/messages', { body, - timeout: this._client._options.timeout ?? - (body.stream ? 600000 : this._client._calculateNonstreamingTimeout(body.max_tokens)), + timeout: timeout ?? 600000, ...options, stream: body.stream ?? false, }); @@ -79777,7 +79978,7 @@ class BaseAnthropic { const expectedTimeout = (60 * 60 * maxTokens) / 128000; if (expectedTimeout > defaultTimeout) { throw new error_AnthropicError('Streaming is strongly recommended for operations that may take longer than 10 minutes. ' + - 'See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details'); + 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); } return defaultTimeout * 1000; } @@ -80016,6 +80217,15 @@ class BaseAnthropic { const jitter = 1 - Math.random() * 0.25; return sleepSeconds * jitter * 1000; } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 60 * 60 * 1000; // 10 minutes + const defaultTime = 60 * 10 * 1000; // 10 minutes + const expectedTime = (maxTime * maxTokens) / 128000; + if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { + throw new error_AnthropicError('Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); + } + return defaultTime; + } buildRequest(inputOptions, { retryCount = 0 } = {}) { const options = { ...inputOptions }; const { method, path, query } = options; @@ -80091,7 +80301,7 @@ class BaseAnthropic { else if (typeof body === 'object' && (Symbol.asyncIterator in body || (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; + return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; } else { return tslib_classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); @@ -80158,10 +80368,10 @@ const v6ToV1 = dist/* v6ToV1 */.JE; const v7 = dist.v7; const NIL = dist/* NIL */.wD; const MAX = dist/* MAX */.Zu; -const version = dist/* version */.rE; +const wrapper_version = dist/* version */.rE; const wrapper_validate = dist/* validate */.tf; const wrapper_stringify = dist/* stringify */.As; -const parse = dist/* parse */.qg; +const wrapper_parse = dist/* parse */.qg; // EXTERNAL MODULE: ./node_modules/@mistralai/mistralai/index.js var mistralai = __nccwpck_require__(6611); @@ -82083,10 +82293,10 @@ function utils_convertToChunk(message) { } } -;// CONCATENATED MODULE: ./node_modules/zod/lib/index.mjs -var util; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/helpers/util.js +var util_util; (function (util) { - util.assertEqual = (val) => val; + util.assertEqual = (_) => { }; function assertIs(_arg) { } util.assertIs = assertIs; function assertNever(_x) { @@ -82133,11 +82343,9 @@ var util; }; util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); } util.joinValues = joinValues; util.jsonStringifyReplacer = (_, value) => { @@ -82146,7 +82354,7 @@ var util; } return value; }; -})(util || (util = {})); +})(util_util || (util_util = {})); var objectUtil; (function (objectUtil) { objectUtil.mergeShapes = (first, second) => { @@ -82156,7 +82364,7 @@ var objectUtil; }; }; })(objectUtil || (objectUtil = {})); -const ZodParsedType = util.arrayToEnum([ +const ZodParsedType = util_util.arrayToEnum([ "string", "nan", "number", @@ -82186,7 +82394,7 @@ const getParsedType = (data) => { case "string": return ZodParsedType.string; case "number": - return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": @@ -82202,10 +82410,7 @@ const getParsedType = (data) => { if (data === null) { return ZodParsedType.null; } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { @@ -82223,7 +82428,9 @@ const getParsedType = (data) => { } }; -const ZodIssueCode = util.arrayToEnum([ +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/ZodError.js + +const ZodIssueCode = util_util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", @@ -82327,7 +82534,7 @@ class ZodError extends Error { return this.message; } get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + return JSON.stringify(this.issues, util_util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; @@ -82355,6 +82562,9 @@ ZodError.create = (issues) => { return error; }; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/locales/en.js + + const errorMap = (issue, _ctx) => { let message; switch (issue.code) { @@ -82367,19 +82577,19 @@ const errorMap = (issue, _ctx) => { } break; case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + message = `Unrecognized key(s) in object: ${util_util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + message = `Invalid discriminator value. Expected ${util_util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + message = `Invalid enum value. Expected ${util_util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; @@ -82405,7 +82615,7 @@ const errorMap = (issue, _ctx) => { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { - util.assertNever(issue.validation); + util_util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { @@ -82421,17 +82631,9 @@ const errorMap = (issue, _ctx) => { else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${issue.minimum}`; + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly equal to ` - : issue.inclusive - ? `greater than or equal to ` - : `greater than `}${new Date(Number(issue.minimum))}`; + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; @@ -82441,23 +82643,11 @@ const errorMap = (issue, _ctx) => { else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") - message = `Date must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `smaller than or equal to` - : `smaller than`} ${new Date(Number(issue.maximum))}`; + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; @@ -82475,12 +82665,16 @@ const errorMap = (issue, _ctx) => { break; default: message = _ctx.defaultError; - util.assertNever(issue); + util_util.assertNever(issue); } return { message }; }; +/* harmony default export */ const en = (errorMap); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/errors.js + +let overrideErrorMap = en; -let overrideErrorMap = errorMap; function setErrorMap(map) { overrideErrorMap = map; } @@ -82488,6 +82682,9 @@ function getErrorMap() { return overrideErrorMap; } +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/helpers/parseUtil.js + + const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; @@ -82527,7 +82724,7 @@ function addIssueToContext(ctx, issueData) { ctx.common.contextualErrorMap, // contextual error map is first priority ctx.schemaErrorMap, // then schema-bound map if available overrideMap, // then global override map - overrideMap === errorMap ? undefined : errorMap, // then global default map + overrideMap === en ? undefined : en, // then global default map ].filter((x) => !!x), }); ctx.common.issues.push(issue); @@ -82579,8 +82776,7 @@ class ParseStatus { status.dirty(); if (value.status === "dirty") status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } @@ -82597,46 +82793,20 @@ const isDirty = (x) => x.status === "dirty"; const isValid = (x) => x.status === "valid"; const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -/****************************************************************************** -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. -***************************************************************************** */ - -function lib_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); -} - -function lib_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; -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/helpers/errorUtil.js var errorUtil; (function (errorUtil) { errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); -var _ZodEnum_cache, _ZodNativeEnum_cache; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/types.js + + + + + class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; @@ -82647,7 +82817,7 @@ class ParseInputLazyPath { } get path() { if (!this._cachedPath.length) { - if (this._key instanceof Array) { + if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { @@ -82687,17 +82857,16 @@ function processCreateParams(params) { if (errorMap) return { errorMap: errorMap, description }; const customMap = (iss, ctx) => { - var _a, _b; const { message } = params; if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; + return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; + return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } @@ -82749,14 +82918,13 @@ class ZodType { throw result.error; } safeParse(data, params) { - var _a; const ctx = { common: { issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], + path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, @@ -82766,7 +82934,6 @@ class ZodType { return handleResult(ctx, result); } "~validate"(data) { - var _a, _b; const ctx = { common: { issues: [], @@ -82790,7 +82957,7 @@ class ZodType { }; } catch (err) { - if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) { + if (err?.message?.toLowerCase()?.includes("encountered")) { this["~standard"].async = true; } ctx.common = { @@ -82817,19 +82984,17 @@ class ZodType { const ctx = { common: { issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, + contextualErrorMap: params?.errorMap, async: true, }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], + path: params?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data), }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { @@ -82873,9 +83038,7 @@ class ZodType { refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { @@ -83092,13 +83255,15 @@ function isValidJWT(jwt, alg) { const decoded = JSON.parse(atob(base64)); if (typeof decoded !== "object" || decoded === null) return false; - if (!decoded.typ || !decoded.alg) + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } - catch (_a) { + catch { return false; } } @@ -83269,7 +83434,7 @@ class ZodString extends ZodType { try { new URL(input.data); } - catch (_a) { + catch { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", @@ -83437,7 +83602,7 @@ class ZodString extends ZodType { } } else { - util.assertNever(check); + util_util.assertNever(check); } } return { status: status.value, value: input.data }; @@ -83499,7 +83664,6 @@ class ZodString extends ZodType { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { - var _a, _b; if (typeof options === "string") { return this._addCheck({ kind: "datetime", @@ -83511,10 +83675,10 @@ class ZodString extends ZodType { } return this._addCheck({ kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), }); } date(message) { @@ -83530,8 +83694,8 @@ class ZodString extends ZodType { } return this._addCheck({ kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), }); } duration(message) { @@ -83548,8 +83712,8 @@ class ZodString extends ZodType { return this._addCheck({ kind: "includes", value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), + position: options?.position, + ...errorUtil.errToObj(options?.message), }); } startsWith(value, message) { @@ -83682,11 +83846,10 @@ class ZodString extends ZodType { } } ZodString.create = (params) => { - var _a; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, + coerce: params?.coerce ?? false, ...processCreateParams(params), }); }; @@ -83695,9 +83858,9 @@ function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; } class ZodNumber extends ZodType { constructor() { @@ -83723,54 +83886,273 @@ class ZodNumber extends ZodType { let ctx = undefined; const status = new ParseStatus(); for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; + if (check.kind === "int") { + if (!util_util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util_util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util_util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } + catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, + type: "bigint", minimum: check.value, - type: "number", inclusive: check.inclusive, - exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, + type: "bigint", maximum: check.value, - type: "number", inclusive: check.inclusive, - exact: false, message: check.message, }); status.dirty(); } } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { + if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, @@ -83780,22 +84162,21 @@ class ZodNumber extends ZodType { status.dirty(); } } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } else { - util.assertNever(check); + util_util.assertNever(check); } } return { status: status.value, value: input.data }; } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } @@ -83809,7 +84190,7 @@ class ZodNumber extends ZodType { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { - return new ZodNumber({ + return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, @@ -83823,21 +84204,15 @@ class ZodNumber extends ZodType { }); } _addCheck(check) { - return new ZodNumber({ + return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check], }); } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); - } positive(message) { return this._addCheck({ kind: "min", - value: 0, + value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); @@ -83845,7 +84220,7 @@ class ZodNumber extends ZodType { negative(message) { return this._addCheck({ kind: "max", - value: 0, + value: BigInt(0), inclusive: false, message: errorUtil.toString(message), }); @@ -83853,7 +84228,7 @@ class ZodNumber extends ZodType { nonpositive(message) { return this._addCheck({ kind: "max", - value: 0, + value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); @@ -83861,7 +84236,7 @@ class ZodNumber extends ZodType { nonnegative(message) { return this._addCheck({ kind: "min", - value: 0, + value: BigInt(0), inclusive: true, message: errorUtil.toString(message), }); @@ -83869,30 +84244,147 @@ class ZodNumber extends ZodType { multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", - value: value, + value, message: errorUtil.toString(message), }); } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util_util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], }); } - safe(message) { + min(minDate, message) { return this._addCheck({ kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, + value: minDate.getTime(), message: errorUtil.toString(message), - })._addCheck({ + }); + } + max(maxDate, message) { + return this._addCheck({ kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, + value: maxDate.getTime(), message: errorUtil.toString(message), }); } - get minValue() { + get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { @@ -83900,9 +84392,9 @@ class ZodNumber extends ZodType { min = ch.value; } } - return min; + return min != null ? new Date(min) : null; } - get maxValue() { + get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { @@ -83910,13374 +84402,21996 @@ class ZodNumber extends ZodType { max = ch.value; } } - return max; + return max != null ? new Date(max) : null; } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util.isInteger(ch.value))); +} +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; +} +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } +} +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); } } - return Number.isFinite(min) && Number.isFinite(max); + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; } -} -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util_util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; } _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } - catch (_a) { - return this._getInvalidInput(input); - } - } const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); } } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, }); - status.dirty(); } } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, }); status.dirty(); } } + else if (unknownKeys === "strip") { + } else { - util.assertNever(check); + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); + get shape() { + return this._def.shape(); } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ + strip() { + return new ZodObject({ ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], + unknownKeys: "strip", }); } - _addCheck(check) { - return new ZodBigInt({ + passthrough() { + return new ZodObject({ ...this._def, - checks: [...this._def.checks, check], + unknownKeys: "passthrough", }); } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), }); } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, }); + return merged; } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, }); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), + pick(mask) { + const shape = {}; + for (const key of util_util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, }); } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), + omit(mask) { + const shape = {}; + for (const key of util_util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, }); } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util_util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); } } - return min; + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + required(mask) { + const newShape = {}; + for (const key of util_util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; } } - return max; + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util_util.objectKeys(this.shape)); } } -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params), }); }; -class ZodBoolean extends ZodType { +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, + code: ZodIssueCode.invalid_union, + unionErrors, }); return INVALID; } - return OK(input.data); + } + get options() { + return this._def.options; } } -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params), }); }; -class ZodDate extends ZodType { +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util_util.objectValues(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } +}; +class ZodDiscriminatedUnion extends ZodType { _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, + expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { addIssueToContext(ctx, { - code: ZodIssueCode.invalid_date, + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], }); return INVALID; } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } - } - else { - util.assertNever(check); + optionsMap.set(value, type); } } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), }); } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); +} +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util_util.objectKeys(b); + const sharedKeys = util_util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; } + newArray.push(sharedValue.data); } - return min != null ? new Date(min) : null; + return { valid: true, data: newArray }; } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; + else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); } - return max != null ? new Date(max) : null; } } -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params), }); }; -class ZodSymbol extends ZodType { +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +class ZodTuple extends ZodType { _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, + expected: ZodParsedType.array, received: ctx.parsedType, }); return INVALID; } - return OK(input.data); - } -} -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); + if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", }); return INVALID; } - return OK(input.data); + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); } } -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, ...processCreateParams(params), }); }; -class ZodNull extends ZodType { +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, + expected: ZodParsedType.object, received: ctx.parsedType, }); return INVALID; } - return OK(input.data); + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } } -} -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; + get element() { + return this._def.valueType; } - _parse(input) { - return OK(input.data); + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); } } -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); -}; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; - } - _parse(input) { - return OK(input.data); +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; } -} -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return INVALID; + get valueSchema() { + return this._def.valueType; } -} -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, + expected: ZodParsedType.map, received: ctx.parsedType, }); return INVALID; } - return OK(input.data); + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } } } -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params), }); }; -class ZodArray extends ZodType { +class ZodSet extends ZodType { _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, + expected: ZodParsedType.set, received: ctx.parsedType, }); return INVALID; } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", + minimum: def.minSize.value, + type: "set", inclusive: true, exact: false, - message: def.minLength.message, + message: def.minSize.message, }); status.dirty(); } } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", + maximum: def.maxSize.value, + type: "set", inclusive: true, exact: false, - message: def.maxLength.message, + message: def.maxSize.message, }); status.dirty(); } } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return ParseStatus.mergeArray(status, result); - }); + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; } - min(minLength, message) { - return new ZodArray({ + min(minSize, message) { + return new ZodSet({ ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, + minSize: { value: minSize, message: errorUtil.toString(message) }, }); } - max(maxLength, message) { - return new ZodArray({ + max(maxSize, message) { + return new ZodSet({ ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, }); } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }); + size(size, message) { + return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } } -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params), }); }; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } -} -class ZodObject extends ZodType { +class ZodFunction extends ZodType { constructor() { super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - return (this._cached = { shape, keys }); + this.validate = this.implement; } _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, + expected: ZodParsedType.function, received: ctx.parsedType, }); return INVALID; } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, }); } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") ; - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; }); } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } } - omit(mask) { - const shape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); + parameters() { + return this._def.args; } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); + returnType() { + return this._def.returns; } - partial(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - }); - return new ZodObject({ + args(...items) { + return new ZodFunction({ ...this._def, - shape: () => newShape, + args: ZodTuple.create(items).rest(ZodUnknown.create()), }); } - required(mask) { - const newShape = {}; - util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - }); - return new ZodObject({ + returns(returnType) { + return new ZodFunction({ ...this._def, - shape: () => newShape, + returns: returnType, }); } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); } } -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +} +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params), }); }; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +} +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params), }); }; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params), }); -}; -class ZodUnion extends ZodType { +} +class ZodEnum extends ZodType { _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - // return invalid - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, + expected: util_util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, }); return INVALID; } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); + if (!this._cache) { + this._cache = new Set(this._def.values); } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError(issues)); + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, }); return INVALID; } + return OK(input.data); } get options() { - return this._def.options; - } -} -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } - else if (type instanceof ZodLiteral) { - return [type.value]; - } - else if (type instanceof ZodEnum) { - return type.options; - } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util.objectValues(type.enum); - } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } - else if (type instanceof ZodUndefined) { - return [undefined]; - } - else if (type instanceof ZodNull) { - return [null]; - } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; + return this._def.values; } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); } - else { - return []; + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); } -}; -class ZodDiscriminatedUnion extends ZodType { +} +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { + const nativeEnumValues = util_util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util_util.objectValues(nativeEnumValues); addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, + expected: util_util.joinValues(expectedValues), received: ctx.parsedType, + code: ZodIssueCode.invalid_type, }); return INVALID; } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { + if (!this._cache) { + this._cache = new Set(util_util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util_util.objectValues(nativeEnumValues); addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, }); return INVALID; } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, + return OK(input.data); + } + get enum() { + return this._def.values; + } +} +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, }); + return INVALID; } - else { - return option._parseSync({ - data: ctx.data, + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { path: ctx.path, - parent: ctx, + errorMap: ctx.common.contextualErrorMap, }); - } - } - get discriminator() { - return this._def.discriminator; + })); } - get options() { - return this._def.options; +} +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; } - get optionsMap() { - return this._def.optionsMap; + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); } - optionsMap.set(value, type); + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); } } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); + util_util.assertNever(effect); + } +} +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; + +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); } -} -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; + unwrap() { + return this._def.innerType; } - else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; +} +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); } - return { valid: true, data: newObj }; + return this._def.innerType._parse(input); } - else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; + unwrap() { + return this._def.innerType; } - else if (aType === ZodParsedType.date && - bType === ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; +} +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); } - else { - return { valid: false }; + removeDefault() { + return this._def.innerType; } } -class ZodIntersection extends ZodType { +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types, - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; } } + removeCatch() { + return this._def.innerType; + } } -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params), }); }; -class ZodTuple extends ZodType { +class ZodNaN extends ZodType { _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, + expected: ZodParsedType.nan, received: ctx.parsedType, }); return INVALID; } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } - else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); + return { status: "valid", value: input.data }; } } -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params), }); }; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; +const BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); } - get valueSchema() { - return this._def.valueType; + unwrap() { + return this._def.type; } +} +class ZodPipeline extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); } else { - return ParseStatus.mergeObjectSync(status, pairs); + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +} +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} + +const late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); +const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; + +const NEVER = INVALID; + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/external.js + + + + + + + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v3/index.js + + + +/* harmony default export */ const esm_v3 = ((/* unused pure expression or super */ null && (z))); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/index.js + + +/* harmony default export */ const esm = ((/* unused pure expression or super */ null && (z3))); + +// EXTERNAL MODULE: ./node_modules/p-retry/index.js +var p_retry = __nccwpck_require__(2103); +// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js +var p_queue_dist = __nccwpck_require__(6459); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js + +// Wrap the default fetch call due to issues with illegal invocations +// in some environments: +// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err +// @ts-expect-error Broad typing to support a range of fetch implementations +const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); +const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); +/** + * Overrides the fetch implementation used for LangSmith calls. + * You should use this if you need to use an implementation of fetch + * other than the default global (e.g. for dealing with proxies). + * @param fetch The new fetch functino to use. + */ +const overrideFetchImplementation = (fetch) => { + globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; +}; +const _globalFetchImplementationIsNodeFetch = () => { + const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; + if (!fetchImpl) + return false; + // Check if the implementation has node-fetch specific properties + return (typeof fetchImpl === "function" && + "Headers" in fetchImpl && + "Request" in fetchImpl && + "Response" in fetchImpl); +}; +/** + * @internal + */ +const _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`→ ${options?.method || "GET"} ${url}`); } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? + DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + console.log(`← ${res.status} ${res.statusText} ${res.url}`); } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), + return res; + }; +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js + + + +const STATUS_NO_RETRY = [ + 400, // Bad Request + 401, // Unauthorized + 403, // Forbidden + 404, // Not Found + 405, // Method Not Allowed + 406, // Not Acceptable + 407, // Proxy Authentication Required + 408, // Request Timeout +]; +const STATUS_IGNORE = [ + 409, // Conflict +]; +/** + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. + */ +class AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - } -} -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedResponseHook", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.debug = params.debug; + if ( true) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist["default"]({ + concurrency: this.maxConcurrency, }); } else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); } + this.onFailedResponseHook = params?.onFailedResponseHook; } -} -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); -}; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + const onFailedResponseHook = this.onFailedResponseHook; + return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); + else { + throw new Error(error); } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); -}; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType, - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap, - ].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - getErrorMap(), - errorMap, - ].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(async function (...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); + }), { + async onFailedAttempt(error) { + if (error.message.startsWith("Cancel") || + error.message.startsWith("TimeoutError") || + error.message.startsWith("AbortError")) { throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const response = error?.response; + const status = response?.status; + if (status) { + if (STATUS_NO_RETRY.includes(+status)) { + throw error; + } + else if (STATUS_IGNORE.includes(+status)) { + return; + } + if (onFailedResponseHook) { + await onFailedResponseHook(response); + } } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; + }, + // If needed we can change some of the defaults here, + // but they're quite sensible. + retries: this.maxRetries, + randomize: true, + }), { throwOnTimeout: true }); } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return this.call(callable, ...args); } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); + fetch(...args) { + return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); } } -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js +function isLangChainMessage( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +message) { + return typeof message?._getType === "function"; } -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; +function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content }, + }; + // Check for presence of keys in additional_kwargs + if (message?.additional_kwargs && + Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; } + return converted; } -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js + +function assertUuid(str, which) { + if (!wrapper_validate(str)) { + const msg = which !== undefined + ? `Invalid UUID for ${which}: ${str}` + : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; } -class ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js +const warnedMessages = {}; +function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - if (!lib_classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - lib_classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!lib_classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); +} + +// EXTERNAL MODULE: ./node_modules/semver/index.js +var semver = __nccwpck_require__(2088); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js + +function isVersionGreaterOrEqual(current_version, target_version) { + const current = parseVersion(current_version); + const target = parseVersion(target_version); + if (!current || !target) { + throw new Error("Invalid version format."); } - get options() { - return this._def.values; + return current.compare(target) >= 0; +} +function parsePromptIdentifier(identifier) { + if (!identifier || + identifier.split("/").length > 2 || + identifier.startsWith("/") || + identifier.endsWith("/") || + identifier.split(":").length > 2) { + throw new Error(`Invalid identifier format: ${identifier}`); } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) { + throw new Error(`Invalid identifier format: ${identifier}`); } - return enumValues; + return [owner, name, commit]; } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; + else { + if (!ownerNamePart) { + throw new Error(`Invalid identifier format: ${identifier}`); } - return enumValues; + return ["-", ownerNamePart, commit]; } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js +function getErrorStackTrace(e) { + if (typeof e !== "object" || e == null) + return undefined; + if (!("stack" in e) || typeof e.stack !== "string") + return undefined; + let stack = e.stack; + const prevLine = `${e}`; + if (stack.startsWith(prevLine)) { + stack = stack.slice(prevLine.length); } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); + if (stack.startsWith("\n")) { + stack = stack.slice(1); } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, + return stack; +} +function printErrorStackTrace(e) { + const stack = getErrorStackTrace(e); + if (stack == null) + return; + console.error(stack); +} +/** + * LangSmithConflictError + * + * Represents an error that occurs when there's a conflict during an operation, + * typically corresponding to HTTP 409 status code responses. + * + * This error is thrown when an attempt to create or modify a resource conflicts + * with the current state of the resource on the server. Common scenarios include: + * - Attempting to create a resource that already exists + * - Trying to update a resource that has been modified by another process + * - Violating a uniqueness constraint in the data + * + * @extends Error + * + * @example + * try { + * await createProject("existingProject"); + * } catch (error) { + * if (error instanceof ConflictError) { + * console.log("A conflict occurred:", error.message); + * // Handle the conflict, e.g., by suggesting a different project name + * } else { + * // Handle other types of errors + * } + * } + * + * @property {string} name - Always set to 'ConflictError' for easy identification + * @property {string} message - Detailed error message including server response + * + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 + */ +class LangSmithConflictError extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.name = "LangSmithConflictError"; + this.status = 409; } } -_ZodEnum_cache = new WeakMap(); -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && - ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - if (!lib_classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - lib_classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f"); - } - if (!lib_classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; +/** + * Throws an appropriate error based on the response status and body. + * + * @param response - The fetch Response object + * @param context - Additional context to include in the error message (e.g., operation being performed) + * @throws {LangSmithConflictError} When the response status is 409 + * @throws {Error} For all other non-ok responses + */ +async function raiseForStatus(response, context, consume) { + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + let errorBody; + if (response.ok) { + if (consume) { + errorBody = await response.text(); } - return OK(input.data); + return; } - get enum() { - return this._def.values; + errorBody = await response.text(); + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; + if (response.status === 409) { + throw new LangSmithConflictError(fullMessage); } + const err = new Error(fullMessage); + err.status = response.status; + throw err; } -_ZodNativeEnum_cache = new WeakMap(); -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && - ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +/* eslint-disable */ +// @ts-nocheck +var LIMIT_REPLACE_NODE = "[...]"; +var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; +var arr = []; +var replacerStack = []; +const encoder = new TextEncoder(); +function fast_safe_stringify_defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER, + }; } -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; +function encodeString(str) { + return encoder.encode(str); +} +// Regular stringify +function serialize(obj, errorContext, replacer, spacer, options) { + try { + const str = JSON.stringify(obj, replacer, spacer); + return encodeString(str); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } + catch (e) { + // Fall back to more complex stringify if circular reference + if (!e.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } + console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); + if (typeof options === "undefined") { + options = fast_safe_stringify_defaultOptions(); } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!isValid(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; + decirc(obj, "", 0, [], undefined, 0, options); + let res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); } else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!isValid(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); } } - util.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); + catch (_) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); + finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } + else { + part[0][part[1]] = part[2]; + } + } } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - removeDefault() { - return this._def.innerType; + return encodeString(res); } } -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([parent, k, val, propertyDescriptor]); } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; + else { + replacerStack.push([val, k, replace]); } } - removeCatch() { - return this._def.innerType; + else { + parent[k] = replace; + arr.push([parent, k, val]); } } -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); -}; -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return INVALID; +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } } - return { status: "valid", value: input.data }; + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options); + } + } + else { + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); } } -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -const BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); +// Stable-stringify +function compareFunction(a, b) { + if (a < b) { + return -1; } - unwrap() { - return this._def.type; + if (a > b) { + return 1; } + return 0; } -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); +function deterministicStringify(obj, replacer, spacer, options) { + if (typeof options === "undefined") { + options = fast_safe_stringify_defaultOptions(); + } + var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; + var res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer); } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + } + } + catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); + part[0][part[1]] = part[2]; } } } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } + return res; } -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); +function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; } - return data; - }; - return isAsync(result) - ? result.then((data) => freeze(data)) - : freeze(result); - } - unwrap() { - return this._def.innerType; + } + try { + if (typeof val.toJSON === "function") { + return; + } + } + catch (_) { + return; + } + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options); + } + } + else { + // Create a temporary object in the required way + var tmp = {}; + var keys = Object.keys(val).sort(compareFunction); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + deterministicDecirc(val[key], key, i, stack, val, depth, options); + tmp[key] = val[key]; + } + if (typeof parent !== "undefined") { + arr.push([parent, k, val]); + parent[k] = tmp; + } + else { + return tmp; + } + } + stack.pop(); } } -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -function cleanParams(params, data) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - const r = check(data); - if (r instanceof Promise) { - return r.then((r) => { - var _a, _b; - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues(replacer) { + replacer = + typeof replacer !== "undefined" + ? replacer + : function (k, v) { + return v; + }; + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } } - return; - }); - return ZodAny.create(); + } + return replacer.call(this, key, val); + }; } -const late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -const stringType = ZodString.create; -const numberType = ZodNumber.create; -const nanType = ZodNaN.create; -const bigIntType = ZodBigInt.create; -const booleanType = ZodBoolean.create; -const dateType = ZodDate.create; -const symbolType = ZodSymbol.create; -const undefinedType = ZodUndefined.create; -const nullType = ZodNull.create; -const anyType = ZodAny.create; -const unknownType = ZodUnknown.create; -const neverType = ZodNever.create; -const voidType = ZodVoid.create; -const arrayType = ZodArray.create; -const objectType = ZodObject.create; -const strictObjectType = ZodObject.strictCreate; -const unionType = ZodUnion.create; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -const intersectionType = ZodIntersection.create; -const tupleType = ZodTuple.create; -const recordType = ZodRecord.create; -const mapType = ZodMap.create; -const setType = ZodSet.create; -const functionType = ZodFunction.create; -const lazyType = ZodLazy.create; -const literalType = ZodLiteral.create; -const enumType = ZodEnum.create; -const nativeEnumType = ZodNativeEnum.create; -const promiseType = ZodPromise.create; -const effectsType = ZodEffects.create; -const optionalType = ZodOptional.create; -const nullableType = ZodNullable.create; -const preprocessType = ZodEffects.createWithPreprocess; -const pipelineType = ZodPipeline.create; -const ostring = () => stringType().optional(); -const onumber = () => numberType().optional(); -const oboolean = () => booleanType().optional(); -const coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; -const NEVER = INVALID; -var z = /*#__PURE__*/Object.freeze({ - __proto__: null, - defaultErrorMap: errorMap, - setErrorMap: setErrorMap, - getErrorMap: getErrorMap, - makeIssue: makeIssue, - EMPTY_PATH: EMPTY_PATH, - addIssueToContext: addIssueToContext, - ParseStatus: ParseStatus, - INVALID: INVALID, - DIRTY: DIRTY, - OK: OK, - isAborted: isAborted, - isDirty: isDirty, - isValid: isValid, - isAsync: isAsync, - get util () { return util; }, - get objectUtil () { return objectUtil; }, - ZodParsedType: ZodParsedType, - getParsedType: getParsedType, - ZodType: ZodType, - datetimeRegex: datetimeRegex, - ZodString: ZodString, - ZodNumber: ZodNumber, - ZodBigInt: ZodBigInt, - ZodBoolean: ZodBoolean, - ZodDate: ZodDate, - ZodSymbol: ZodSymbol, - ZodUndefined: ZodUndefined, - ZodNull: ZodNull, - ZodAny: ZodAny, - ZodUnknown: ZodUnknown, - ZodNever: ZodNever, - ZodVoid: ZodVoid, - ZodArray: ZodArray, - ZodObject: ZodObject, - ZodUnion: ZodUnion, - ZodDiscriminatedUnion: ZodDiscriminatedUnion, - ZodIntersection: ZodIntersection, - ZodTuple: ZodTuple, - ZodRecord: ZodRecord, - ZodMap: ZodMap, - ZodSet: ZodSet, - ZodFunction: ZodFunction, - ZodLazy: ZodLazy, - ZodLiteral: ZodLiteral, - ZodEnum: ZodEnum, - ZodNativeEnum: ZodNativeEnum, - ZodPromise: ZodPromise, - ZodEffects: ZodEffects, - ZodTransformer: ZodEffects, - ZodOptional: ZodOptional, - ZodNullable: ZodNullable, - ZodDefault: ZodDefault, - ZodCatch: ZodCatch, - ZodNaN: ZodNaN, - BRAND: BRAND, - ZodBranded: ZodBranded, - ZodPipeline: ZodPipeline, - ZodReadonly: ZodReadonly, - custom: custom, - Schema: ZodType, - ZodSchema: ZodType, - late: late, - get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; }, - coerce: coerce, - any: anyType, - array: arrayType, - bigint: bigIntType, - boolean: booleanType, - date: dateType, - discriminatedUnion: discriminatedUnionType, - effect: effectsType, - 'enum': enumType, - 'function': functionType, - 'instanceof': instanceOfType, - intersection: intersectionType, - lazy: lazyType, - literal: literalType, - map: mapType, - nan: nanType, - nativeEnum: nativeEnumType, - never: neverType, - 'null': nullType, - nullable: nullableType, - number: numberType, - object: objectType, - oboolean: oboolean, - onumber: onumber, - optional: optionalType, - ostring: ostring, - pipeline: pipelineType, - preprocess: preprocessType, - promise: promiseType, - record: recordType, - set: setType, - strictObject: strictObjectType, - string: stringType, - symbol: symbolType, - transformer: effectsType, - tuple: tupleType, - 'undefined': undefinedType, - union: unionType, - unknown: unknownType, - 'void': voidType, - NEVER: NEVER, - ZodIssueCode: ZodIssueCode, - quotelessJson: quotelessJson, - ZodError: ZodError -}); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js -// EXTERNAL MODULE: ./node_modules/p-retry/index.js -var p_retry = __nccwpck_require__(2103); -// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js -var p_queue_dist = __nccwpck_require__(6459); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js -// Wrap the default fetch call due to issues with illegal invocations -// in some environments: -// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err -// @ts-expect-error Broad typing to support a range of fetch implementations -const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); -const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); -/** - * Overrides the fetch implementation used for LangSmith calls. - * You should use this if you need to use an implementation of fetch - * other than the default global (e.g. for dealing with proxies). - * @param fetch The new fetch functino to use. - */ -const overrideFetchImplementation = (fetch) => { - globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; + + + + + + + +function mergeRuntimeEnvIntoRunCreate(run) { + const runtimeEnv = getRuntimeEnvironment(); + const envVars = getLangChainEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime, + }, + metadata: { + ...envVars, + ...(envVars.revision_id || run.revision_id + ? { revision_id: run.revision_id ?? envVars.revision_id } + : {}), + ...metadata, + }, + }; + return run; +} +const getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? + getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === undefined) { + return undefined; + } + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) { + throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); + } + return samplingRate; }; -/** - * @internal - */ -const _getFetchImplementation = (debug) => { - return async (...args) => { - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - const [url, options] = args; - console.log(`→ ${options?.method || "GET"} ${url}`); +// utility functions +const isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); +}; +async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return result; +} +function trimQuotes(str) { + if (str === undefined) { + return undefined; + } + return str + .trim() + .replace(/^"(.*)"$/, "$1") + .replace(/^'(.*)'$/, "$1"); +} +const handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + // Return directly after calling this check + return true; + } + } + // Fall back to existing status checks + return false; +}; +function _formatFeedbackScore(score) { + if (typeof score === "number") { + // Truncate at 4 decimal places + return Number(score.toFixed(4)); + } + return score; +} +class AutoBatchQueue { + constructor() { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + } + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + // Setting itemPromiseResolve is synchronous with promise creation: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise + itemPromiseResolve = resolve; + }); + const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; + this.items.push({ + action: item.action, + payload: item.item, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + itemPromiseResolve: itemPromiseResolve, + itemPromise, + size, + }); + this.sizeBytes += size; + return itemPromise; + } + pop(upToSizeBytes) { + if (upToSizeBytes < 1) { + throw new Error("Number of bytes to pop off may not be less than 1."); } - const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? - DEFAULT_FETCH_IMPLEMENTATION)(...args); - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - console.log(`← ${res.status} ${res.statusText} ${res.url}`); + const popped = []; + let poppedSizeBytes = 0; + // Pop items until we reach or exceed the size limit + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && + this.items.length > 0) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } } - return res; - }; -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js - - - -const STATUS_NO_RETRY = [ - 400, // Bad Request - 401, // Unauthorized - 403, // Forbidden - 404, // Not Found - 405, // Method Not Allowed - 406, // Not Acceptable - 407, // Proxy Authentication Required - 408, // Request Timeout -]; -const STATUS_IGNORE = [ - 409, // Conflict -]; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { + // If there is an item on the queue we were unable to pop, + // just return it as a single batch. + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + return [ + popped.map((it) => ({ action: it.action, item: it.payload })), + () => popped.forEach((it) => it.itemPromiseResolve()), + ]; + } +} +// 20 MB +const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520; +const SERVER_INFO_REQUEST_TIMEOUT = 2500; +class Client { + constructor(config = {}) { + Object.defineProperty(this, "apiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "maxRetries", { + Object.defineProperty(this, "apiUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "queue", { + Object.defineProperty(this, "webUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "onFailedResponseHook", { + Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "debug", { + Object.defineProperty(this, "batchIngestCaller", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.debug = params.debug; - if ( true) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist["default"]({ - concurrency: this.maxConcurrency, - }); + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "hideInputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "hideOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingSampleRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: new AutoBatchQueue() + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) { + this.apiUrl = this.apiUrl.slice(0, -1); + } + this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) { + this.webUrl = this.webUrl.slice(0, -1); + } + this.timeout_ms = config.timeout_ms ?? 90_000; + this.caller = new AsyncCaller({ + ...(config.callerOptions ?? {}), + debug: config.debug ?? this.debug, + }); + this.traceBatchConcurrency = + config.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) { + throw new Error("Trace batch concurrency must be positive."); + } + this.debug = config.debug ?? this.debug; + this.batchIngestCaller = new AsyncCaller({ + maxRetries: 2, + maxConcurrency: this.traceBatchConcurrency, + ...(config.callerOptions ?? {}), + onFailedResponseHook: handle429, + debug: config.debug ?? this.debug, + }); + this.hideInputs = + config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = + config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; + this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; + this.blockOnRootRunFinalization = + config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config.batchSizeBytesLimit; + this.fetchOptions = config.fetchOptions || {}; + this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + } + static getDefaultClientConfig() { + const apiKey = getLangSmithEnvironmentVariable("API_KEY"); + const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? + "https://api.smith.langchain.com"; + const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; + const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; + return { + apiUrl: apiUrl, + apiKey: apiKey, + webUrl: undefined, + hideInputs: hideInputs, + hideOutputs: hideOutputs, + }; + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; + } + else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; + } + else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; + } + else if (this.apiUrl.includes("/api") && + !this.apiUrl.split(".", 1)[0].endsWith("api")) { + this.webUrl = this.apiUrl.replace("/api", ""); + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; } else { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; } - this.onFailedResponseHook = params?.onFailedResponseHook; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - const onFailedResponseHook = this.onFailedResponseHook; - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; + get headers() { + const headers = { + "User-Agent": `langsmith-js/${__version__}`, + }; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; + } + return headers; + } + async processInputs(inputs) { + if (this.hideInputs === false) { + return inputs; + } + if (this.hideInputs === true) { + return {}; + } + if (typeof this.hideInputs === "function") { + return this.hideInputs(inputs); + } + return inputs; + } + async processOutputs(outputs) { + if (this.hideOutputs === false) { + return outputs; + } + if (this.hideOutputs === true) { + return {}; + } + if (typeof this.hideOutputs === "function") { + return this.hideOutputs(outputs); + } + return outputs; + } + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== undefined) { + runParams.inputs = await this.processInputs(runParams.inputs); + } + if (runParams.outputs !== undefined) { + runParams.outputs = await this.processOutputs(runParams.outputs); + } + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + return response; + } + async _get(path, queryParams) { + const response = await this._getResponse(path, queryParams); + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = transform + ? transform(await response.json()) + : await response.json(); + if (items.length === 0) { + break; } - else { - throw new Error(error); + yield items; + if (items.length < limit) { + break; } - }), { - async onFailedAttempt(error) { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.message.startsWith("AbortError")) { - throw error; + offset += items.length; + } + } + async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { + const bodyParams = body ? { ...body } : {}; + while (true) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { + method: requestMethod, + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(bodyParams), + }); + const responseBody = await response.json(); + if (!responseBody) { + break; + } + if (!responseBody[dataKey]) { + break; + } + yield responseBody[dataKey]; + const cursors = responseBody.cursors; + if (!cursors) { + break; + } + if (!cursors.next) { + break; + } + bodyParams.cursor = cursors.next; + } + } + // Allows mocking for tests + _shouldSample() { + if (this.tracingSampleRate === undefined) { + return true; + } + return Math.random() < this.tracingSampleRate; + } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === undefined) { + return runs; + } + if (patch) { + const sampled = []; + for (const run of runs) { + if (!this.filteredPostUuids.has(run.id)) { + sampled.push(run); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; + else { + this.filteredPostUuids.delete(run.id); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const response = error?.response; - const status = response?.status; - if (status) { - if (STATUS_NO_RETRY.includes(+status)) { - throw error; - } - else if (STATUS_IGNORE.includes(+status)) { - return; + } + return sampled; + } + else { + // For new runs, sample at trace level to maintain consistency + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + // If we've already made a decision about this trace, follow it + if (this.filteredPostUuids.has(traceId)) { + continue; + } + // For new traces, apply sampling + if (run.id === traceId) { + if (this._shouldSample()) { + sampled.push(run); } - if (onFailedResponseHook) { - await onFailedResponseHook(response); + else { + this.filteredPostUuids.add(traceId); } } - }, - // If needed we can change some of the defaults here, - // but they're quite sensible. - retries: this.maxRetries, - randomize: true, - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); + else { + // Child runs follow their trace's sampling decision + sampled.push(run); + } + } + return sampled; } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content }, - }; - // Check for presence of keys in additional_kwargs - if (message?.additional_kwargs && - Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; - } - return converted; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js - -function assertUuid(str, which) { - if (!wrapper_validate(str)) { - const msg = which !== undefined - ? `Invalid UUID for ${which}: ${str}` - : `Invalid UUID: ${str}`; - throw new Error(msg); - } - return str; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js -const warnedMessages = {}; -function warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; } -} - -// EXTERNAL MODULE: ./node_modules/semver/index.js -var semver = __nccwpck_require__(2088); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js - -function isVersionGreaterOrEqual(current_version, target_version) { - const current = parseVersion(current_version); - const target = parseVersion(target_version); - if (!current || !target) { - throw new Error("Invalid version format."); + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return (this.batchSizeBytesLimit ?? + serverInfo.batch_ingest_config?.size_limit_bytes ?? + DEFAULT_BATCH_SIZE_LIMIT_BYTES); } - return current.compare(target) >= 0; -} -function parsePromptIdentifier(identifier) { - if (!identifier || - identifier.split("/").length > 2 || - identifier.startsWith("/") || - identifier.endsWith("/") || - identifier.split(":").length > 2) { - throw new Error(`Invalid identifier format: ${identifier}`); + async _getMultiPartSupport() { + const serverInfo = await this._ensureServerInfo(); + return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); } - const [ownerNamePart, commitPart] = identifier.split(":"); - const commit = commitPart || "latest"; - if (ownerNamePart.includes("/")) { - const [owner, name] = ownerNamePart.split("/", 2); - if (!owner || !name) { - throw new Error(`Invalid identifier format: ${identifier}`); + drainAutoBatchQueue(batchSizeLimit) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); + if (!batch.length) { + done(); + break; + } + const batchPromise = this._processBatch(batch, done).catch(console.error); + promises.push(batchPromise); } - return [owner, name, commit]; + return Promise.all(promises); } - else { - if (!ownerNamePart) { - throw new Error(`Invalid identifier format: ${identifier}`); + async _processBatch(batch, done) { + if (!batch.length) { + done(); + return; + } + try { + const ingestParams = { + runCreates: batch + .filter((item) => item.action === "create") + .map((item) => item.item), + runUpdates: batch + .filter((item) => item.action === "update") + .map((item) => item.item), + }; + const serverInfo = await this._ensureServerInfo(); + if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { + await this.multipartIngestRuns(ingestParams); + } + else { + await this.batchIngestRuns(ingestParams); + } + } + finally { + done(); } - return ["-", ownerNamePart, commit]; } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js -function getErrorStackTrace(e) { - if (typeof e !== "object" || e == null) - return undefined; - if (!("stack" in e) || typeof e.stack !== "string") - return undefined; - let stack = e.stack; - const prevLine = `${e}`; - if (stack.startsWith(prevLine)) { - stack = stack.slice(prevLine.length); + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = undefined; + if (item.action === "create") { + item.item = mergeRuntimeEnvIntoRunCreate(item.item); + } + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) { + // Rely on manual flushing in serverless environments + return itemPromise; + } + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { + void this.drainAutoBatchQueue(sizeLimitBytes); + } + if (this.autoBatchQueue.items.length > 0) { + this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = undefined; + void this.drainAutoBatchQueue(sizeLimitBytes); + }, this.autoBatchAggregationDelayMs); + } + return itemPromise; } - if (stack.startsWith("\n")) { - stack = stack.slice(1); + async _getServerInfo() { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/info`, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), + ...this.fetchOptions, + }); + await raiseForStatus(response, "get server info"); + const json = await response.json(); + if (this.debug) { + console.log("\n=== LangSmith Server Configuration ===\n" + + JSON.stringify(json, null, 2) + + "\n"); + } + return json; } - return stack; -} -function printErrorStackTrace(e) { - const stack = getErrorStackTrace(e); - if (stack == null) - return; - console.error(stack); -} -/** - * LangSmithConflictError - * - * Represents an error that occurs when there's a conflict during an operation, - * typically corresponding to HTTP 409 status code responses. - * - * This error is thrown when an attempt to create or modify a resource conflicts - * with the current state of the resource on the server. Common scenarios include: - * - Attempting to create a resource that already exists - * - Trying to update a resource that has been modified by another process - * - Violating a uniqueness constraint in the data - * - * @extends Error - * - * @example - * try { - * await createProject("existingProject"); - * } catch (error) { - * if (error instanceof ConflictError) { - * console.log("A conflict occurred:", error.message); - * // Handle the conflict, e.g., by suggesting a different project name - * } else { - * // Handle other types of errors - * } - * } - * - * @property {string} name - Always set to 'ConflictError' for easy identification - * @property {string} message - Detailed error message including server response - * - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 - */ -class LangSmithConflictError extends Error { - constructor(message) { - super(message); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + async _ensureServerInfo() { + if (this._getServerInfoPromise === undefined) { + this._getServerInfoPromise = (async () => { + if (this._serverInfo === undefined) { + try { + this._serverInfo = await this._getServerInfo(); + } + catch (e) { + console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); + } + } + return this._serverInfo ?? {}; + })(); + } + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === undefined) { + this._getServerInfoPromise = undefined; + } + return serverInfo; }); - this.name = "LangSmithConflictError"; - this.status = 409; } -} -/** - * Throws an appropriate error based on the response status and body. - * - * @param response - The fetch Response object - * @param context - Additional context to include in the error message (e.g., operation being performed) - * @throws {LangSmithConflictError} When the response status is 409 - * @throws {Error} For all other non-ok responses - */ -async function raiseForStatus(response, context, consume) { - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - let errorBody; - if (response.ok) { - if (consume) { - errorBody = await response.text(); + async _getSettings() { + if (!this.settings) { + this.settings = this._get("/settings"); } - return; + return await this.settings; } - errorBody = await response.text(); - const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; - if (response.status === 409) { - throw new LangSmithConflictError(fullMessage); + /** + * Flushes current queued traces. + */ + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + await this.drainAutoBatchQueue(sizeLimitBytes); } - const err = new Error(fullMessage); - err.status = response.status; - throw err; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js -/* eslint-disable */ -// @ts-nocheck -var LIMIT_REPLACE_NODE = "[...]"; -var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; -var arr = []; -var replacerStack = []; -const encoder = new TextEncoder(); -function fast_safe_stringify_defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER, - }; -} -function encodeString(str) { - return encoder.encode(str); -} -// Regular stringify -function serialize(obj, replacer, spacer, options) { - try { - const str = JSON.stringify(obj, replacer, spacer); - return encodeString(str); + async createRun(run) { + if (!this._filterForSampling([run]).length) { + return; + } + const headers = { ...this.headers, "Content-Type": "application/json" }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await this.prepareRunCreateOrUpdateInputs({ + session_name, + ...run, + start_time: run.start_time ?? Date.now(), + }); + if (this.autoBatchTracing && + runCreate.trace_id !== undefined && + runCreate.dotted_order !== undefined) { + void this.processRunOperation({ + action: "create", + item: runCreate, + }).catch(console.error); + return; + } + const mergedRunCreateParam = mergeRuntimeEnvIntoRunCreate(runCreate); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs`, { + method: "POST", + headers, + body: serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create run", true); } - catch (e) { - // Fall back to more complex stringify if circular reference - if (!e.message?.includes("Converting circular structure to JSON")) { - console.warn("[WARNING]: LangSmith received unserializable value."); - return encodeString("[Unserializable]"); + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates, }) { + if (runCreates === undefined && runUpdates === undefined) { + return; } - console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance."); - if (typeof options === "undefined") { - options = fast_safe_stringify_defaultOptions(); + let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); + let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; + } + else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; } - decirc(obj, "", 0, [], undefined, 0, options); - let res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer); + const rawBatch = { + post: preparedCreateParams, + patch: preparedUpdateParams, + }; + if (!rawBatch.post.length && !rawBatch.patch.length) { + return; + } + const batchChunks = { + post: [], + patch: [], + }; + for (const k of ["post", "patch"]) { + const key = k; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== undefined) { + // Type is wrong but this is a deprecated code path anyway + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); } - else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post + .map((item) => item.id) + .concat(batchChunks.patch.map((item) => item.id)) + .join(","); + await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`)); + } + } + async _postBatchIngestRuns(body) { + const headers = { + ...this.headers, + "Content-Type": "application/json", + Accept: "application/json", + }; + const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/batch`, { + method: "POST", + headers, + body: body, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "batch create run", true); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async multipartIngestRuns({ runCreates, runUpdates, }) { + if (runCreates === undefined && runUpdates === undefined) { + return; + } + // transform and convert to dicts + const allAttachments = {}; + let preparedCreateParams = []; + for (const create of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); + if (preparedCreate.id !== undefined && + preparedCreate.attachments !== undefined) { + allAttachments[preparedCreate.id] = preparedCreate.attachments; } + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); } - catch (_) { - return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + let preparedUpdateParams = []; + for (const update of runUpdates ?? []) { + preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); } - finally { - while (arr.length !== 0) { - const part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); + // require trace_id and dotted_order + const invalidRunCreate = preparedCreateParams.find((runCreate) => { + return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); + }); + if (invalidRunCreate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + } + const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { + return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); + }); + if (invalidRunUpdate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + } + // combine post and patch dicts where possible + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; } else { - part[0][part[1]] = part[2]; + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + if (preparedCreateParams.length === 0 && + preparedUpdateParams.length === 0) { + return; + } + // send the runs in multipart requests + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [ + ["post", preparedCreateParams], + ["patch", preparedUpdateParams], + ]) { + for (const originalPayload of payloads) { + // collect fields to be sent as separate parts + const { inputs, outputs, events, attachments, ...payload } = originalPayload; + const fields = { inputs, outputs, events }; + // encode the main run payload + const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { + type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip + }), + }); + // encode the fields we collected + for (const [key, value] of Object.entries(fields)) { + if (value === undefined) { + continue; + } + const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { + type: `application/json; length=${stringifiedValue.length}`, + }), + }); + } + // encode the attachments + if (payload.id !== undefined) { + const attachments = allAttachments[payload.id]; + if (attachments) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments)) { + let contentType; + let content; + if (Array.isArray(attachment)) { + [contentType, content] = attachment; + } + else { + contentType = attachment.mimeType; + content = attachment.data; + } + // Validate that the attachment name doesn't contain a '.' + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + + `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { + type: `${contentType}; length=${content.byteLength}`, + }), + }); + } + } } + // compute context + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); } } - return encodeString(res); + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; ")); } -} -function setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - arr.push([parent, k, val, propertyDescriptor]); + async _createNodeFetchBody(parts, boundary) { + // Create multipart form data manually using Blobs + const chunks = []; + for (const part of parts) { + // Add field boundary + chunks.push(new Blob([`--${boundary}\r\n`])); + chunks.push(new Blob([ + `Content-Disposition: form-data; name="${part.name}"\r\n`, + `Content-Type: ${part.payload.type}\r\n\r\n`, + ])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + // Add final boundary + chunks.push(new Blob([`--${boundary}--\r\n`])); + // Combine all chunks into a single Blob + const body = new Blob(chunks); + // Convert Blob to ArrayBuffer for compatibility + const arrayBuffer = await body.arrayBuffer(); + return arrayBuffer; + } + async _createMultipartStream(parts, boundary) { + const encoder = new TextEncoder(); + // Create a ReadableStream for streaming the multipart data + // Only do special handling if we're using node-fetch + const stream = new ReadableStream({ + async start(controller) { + // Helper function to write a chunk to the stream + const writeChunk = async (chunk) => { + if (typeof chunk === "string") { + controller.enqueue(encoder.encode(chunk)); + } + else { + controller.enqueue(chunk); + } + }; + // Write each part to the stream + for (const part of parts) { + // Write boundary and headers + await writeChunk(`--${boundary}\r\n`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); + await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); + // Write the payload + const payloadStream = part.payload.stream(); + const reader = payloadStream.getReader(); + try { + let result; + while (!(result = await reader.read()).done) { + controller.enqueue(result.value); + } + } + finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + // Write final boundary + await writeChunk(`--${boundary}--\r\n`); + controller.close(); + }, + }); + return stream; + } + async _sendMultipartRequest(parts, context) { + try { + // Create multipart form data boundary + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const body = await (_globalFetchImplementationIsNodeFetch() + ? this._createNodeFetchBody(parts, boundary) + : this._createMultipartStream(parts, boundary)); + const res = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/multipart`, { + method: "POST", + headers: { + ...this.headers, + "Content-Type": `multipart/form-data; boundary=${boundary}`, + }, + body, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "ingest multipart runs", true); + // eslint-disable-next-line @typescript-eslint/no-explicit-any } - else { - replacerStack.push([val, k, replace]); + catch (e) { + console.warn(`${e.message.trim()}\n\nContext: ${context}`); } } - else { - parent[k] = replace; - arr.push([parent, k, val]); - } -} -function decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } + async updateRun(runId, run) { + assertUuid(runId); + if (run.inputs) { + run.inputs = await this.processInputs(run.inputs); } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + if (run.outputs) { + run.outputs = await this.processOutputs(run.outputs); } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); + // TODO: Untangle types + const data = { ...run, id: runId }; + if (!this._filterForSampling([data], true).length) { return; } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options); + if (this.autoBatchTracing && + data.trace_id !== undefined && + data.dotted_order !== undefined) { + if (run.end_time !== undefined && + data.parent_run_id === undefined && + this.blockOnRootRunFinalization && + !this.manualFlushMode) { + // Trigger batches as soon as a root trace ends and wait to ensure trace finishes + // in serverless environments. + await this.processRunOperation({ action: "update", item: data }).catch(console.error); + return; } - } - else { - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - decirc(val[key], key, i, stack, val, depth, options); + else { + void this.processRunOperation({ action: "update", item: data }).catch(console.error); } + return; } - stack.pop(); - } -} -// Stable-stringify -function compareFunction(a, b) { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} -function deterministicStringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") { - options = fast_safe_stringify_defaultOptions(); + const headers = { ...this.headers, "Content-Type": "application/json" }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + body: serialize(run, `Serializing payload to update run with id: ${runId}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update run", true); } - var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; - var res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer); - } - else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns) { + run = await this._loadChildRuns(run); } + return run; } - catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } - finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); + async getRunUrl({ runId, run, projectOpts, }) { + if (run !== undefined) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; } - else { - part[0][part[1]] = part[2]; + else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; } - } - } - return res; -} -function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; + else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; } - } - try { - if (typeof val.toJSON === "function") { - return; + else { + const project = await this.readProject({ + projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", + }); + sessionId = project.id; } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; } - catch (_) { - return; - } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options); + else if (runId !== undefined) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; } else { - // Create a temporary object in the required way - var tmp = {}; - var keys = Object.keys(val).sort(compareFunction); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - deterministicDecirc(val[key], key, i, stack, val, depth, options); - tmp[key] = val[key]; + throw new Error("Must provide either runId or run"); + } + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id, + })); + const treemap = {}; + const runs = {}; + // TODO: make dotted order required when the migration finishes + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || + childRun.parent_run_id === undefined) { + throw new Error(`Child run ${childRun.id} has no parent`); } - if (typeof parent !== "undefined") { - arr.push([parent, k, val]); - parent[k] = tmp; + if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && + childRun.id !== run.id) { + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; } - else { - return tmp; + } + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; } } - stack.pop(); + return run; } -} -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues(replacer) { - replacer = - typeof replacer !== "undefined" - ? replacer - : function (k, v) { - return v; - }; - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - replacerStack.splice(i, 1); + /** + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. + * + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); + * + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); + * + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); + */ + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; + let projectIds = []; + if (projectId) { + projectIds = Array.isArray(projectId) ? projectId : [projectId]; + } + if (projectName) { + const projectNames = Array.isArray(projectName) + ? projectName + : [projectName]; + const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); + projectIds.push(...projectIds_); + } + const default_select = [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id", + ]; + const body = { + session: projectIds.length ? projectIds : null, + run_type: runType, + reference_example: referenceExampleId, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + execution_order: executionOrder, + parent_run: parentRunId, + start_time: startTime ? startTime.toISOString() : null, + error, + id, + limit, + trace: traceId, + select: select ? select : default_select, + is_root: isRoot, + order, + }; + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + if (limit) { + if (runsYielded >= limit) { + break; + } + if (runs.length + runsYielded > limit) { + const newRuns = runs.slice(0, limit - runsYielded); + yield* newRuns; break; } + runsYielded += runs.length; + yield* runs; + } + else { + yield* runs; } } - return replacer.call(this, key, val); - }; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js - - - - - - - - - - - -function mergeRuntimeEnvIntoRunCreate(run) { - const runtimeEnv = getRuntimeEnvironment(); - const envVars = getLangChainEnvVarsMetadata(); - const extra = run.extra ?? {}; - const metadata = extra.metadata; - run.extra = { - ...extra, - runtime: { - ...runtimeEnv, - ...extra?.runtime, - }, - metadata: { - ...envVars, - ...(envVars.revision_id || run.revision_id - ? { revision_id: run.revision_id ?? envVars.revision_id } - : {}), - ...metadata, - }, - }; - return run; -} -const getTracingSamplingRate = (configRate) => { - const samplingRateStr = configRate?.toString() ?? - getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); - if (samplingRateStr === undefined) { - return undefined; - } - const samplingRate = parseFloat(samplingRateStr); - if (samplingRate < 0 || samplingRate > 1) { - throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); - } - return samplingRate; -}; -// utility functions -const isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); -}; -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); - } - return result; -} -function trimQuotes(str) { - if (str === undefined) { - return undefined; } - return str - .trim() - .replace(/^"(.*)"$/, "$1") - .replace(/^'(.*)'$/, "$1"); -} -const handle429 = async (response) => { - if (response?.status === 429) { - const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000; - if (retryAfter > 0) { - await new Promise((resolve) => setTimeout(resolve, retryAfter)); - // Return directly after calling this check - return true; + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; + const sessionId = projectId || (await this.readProject({ projectName })).id; + const baseBody = { + session_id: sessionId, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100, + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset, + }; + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); + const response = await this.caller.call(_getFetchImplementation(), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = await response.json(); + const { groups, total } = items; + if (groups.length === 0) { + break; + } + for (const thread of groups) { + yield thread; + } + currentOffset += groups.length; + if (currentOffset >= total) { + break; + } } } - // Fall back to existing status checks - return false; -}; -function _formatFeedbackScore(score) { - if (typeof score === "number") { - // Truncate at 4 decimal places - return Number(score.toFixed(4)); + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { + let projectIds_ = projectIds || []; + if (projectNames) { + projectIds_ = [ + ...(projectIds || []), + ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), + ]; + } + const payload = { + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType, + }; + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { + method: "POST", + headers: this.headers, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const result = await response.json(); + return result; } - return score; -} -class AutoBatchQueue { - constructor() { - Object.defineProperty(this, "items", { - enumerable: true, - configurable: true, - writable: true, - value: [] + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4(), + }; + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "sizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async unshareRun(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); + await raiseForStatus(response, "unshare run", true); } - peek() { - return this.items[0]; + async readRunSharedLink(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return undefined; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } - push(item) { - let itemPromiseResolve; - const itemPromise = new Promise((resolve) => { - // Setting itemPromiseResolve is synchronous with promise creation: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise - itemPromiseResolve = resolve; + async listSharedRuns(shareToken, { runIds, } = {}) { + const queryParams = new URLSearchParams({ + share_token: shareToken, }); - const size = serialize(item.item).length; - this.items.push({ - action: item.action, - payload: item.item, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - itemPromiseResolve: itemPromiseResolve, - itemPromise, - size, + if (runIds !== undefined) { + for (const runId of runIds) { + queryParams.append("id", runId); + } + } + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - this.sizeBytes += size; - return itemPromise; + const runs = await response.json(); + return runs; } - pop(upToSizeBytes) { - if (upToSizeBytes < 1) { - throw new Error("Number of bytes to pop off may not be less than 1."); - } - const popped = []; - let poppedSizeBytes = 0; - // Pop items until we reach or exceed the size limit - while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && - this.items.length > 0) { - const item = this.items.shift(); - if (item) { - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); } - // If there is an item on the queue we were unable to pop, - // just return it as a single batch. - if (popped.length === 0 && this.items.length > 0) { - const item = this.items.shift(); - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; } - return [ - popped.map((it) => ({ action: it.action, item: it.payload })), - () => popped.forEach((it) => it.itemPromiseResolve()), - ]; - } -} -// 20 MB -const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520; -const SERVER_INFO_REQUEST_TIMEOUT = 2500; -class Client { - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchIngestCaller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "hideInputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "hideOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingSampleRate", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "filteredPostUuids", { - enumerable: true, - configurable: true, - writable: true, - value: new Set() - }); - Object.defineProperty(this, "autoBatchTracing", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "autoBatchQueue", { - enumerable: true, - configurable: true, - writable: true, - value: new AutoBatchQueue() - }); - Object.defineProperty(this, "autoBatchTimeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "autoBatchAggregationDelayMs", { - enumerable: true, - configurable: true, - writable: true, - value: 250 - }); - Object.defineProperty(this, "batchSizeBytesLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchOptions", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "settings", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "blockOnRootRunFinalization", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "traceBatchConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: 5 + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async shareDataset(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + const data = { + dataset_id: datasetId, + }; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "_serverInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "_getServerInfoPromise", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + await raiseForStatus(response, "unshare dataset", true); + } + async readSharedDataset(shareToken) { + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "manualFlushMode", { - enumerable: true, - configurable: true, - writable: true, - value: false + const dataset = await response.json(); + return dataset; + } + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) { + params.id = options.exampleIds; + } + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => urlParams.append(key, v)); + } + else { + urlParams.append(key, value); + } }); - Object.defineProperty(this, "debug", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - const defaultConfig = Client.getDefaultClientConfig(); - this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - if (this.apiUrl.endsWith("/")) { - this.apiUrl = this.apiUrl.slice(0, -1); + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) { + throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) + ? result.detail.join("\n") + : "Unspecified error"}`); + } + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); } - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - if (this.webUrl?.endsWith("/")) { - this.webUrl = this.webUrl.slice(0, -1); + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl(), + })); + } + async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { + const upsert_ = upsert ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const extra = projectExtra || {}; + if (metadata) { + extra["metadata"] = metadata; } - this.timeout_ms = config.timeout_ms ?? 90_000; - this.caller = new AsyncCaller({ - ...(config.callerOptions ?? {}), - debug: config.debug ?? this.debug, - }); - this.traceBatchConcurrency = - config.traceBatchConcurrency ?? this.traceBatchConcurrency; - if (this.traceBatchConcurrency < 1) { - throw new Error("Trace batch concurrency must be positive."); + const body = { + name: projectName, + extra, + description, + }; + if (referenceDatasetId !== null) { + body["reference_dataset_id"] = referenceDatasetId; } - this.debug = config.debug ?? this.debug; - this.batchIngestCaller = new AsyncCaller({ - maxRetries: 2, - maxConcurrency: this.traceBatchConcurrency, - ...(config.callerOptions ?? {}), - onFailedResponseHook: handle429, - debug: config.debug ?? this.debug, + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - this.hideInputs = - config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; - this.hideOutputs = - config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; - this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; - this.blockOnRootRunFinalization = - config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; - this.batchSizeBytesLimit = config.batchSizeBytesLimit; - this.fetchOptions = config.fetchOptions || {}; - this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + await raiseForStatus(response, "create project"); + const result = await response.json(); + return result; } - static getDefaultClientConfig() { - const apiKey = getLangSmithEnvironmentVariable("API_KEY"); - const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? - "https://api.smith.langchain.com"; - const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; - const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; - return { - apiUrl: apiUrl, - apiKey: apiKey, - webUrl: undefined, - hideInputs: hideInputs, - hideOutputs: hideOutputs, + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) { + extra = { ...(extra || {}), metadata }; + } + const body = { + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null, }; + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update project"); + const result = await response.json(); + return result; } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; + async hasProject({ projectId, projectName, }) { + // TODO: Add a head request + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); } - else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost:3000"; - return this.webUrl; + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; } - else if (this.apiUrl.endsWith("/api/v1")) { - this.webUrl = this.apiUrl.replace("/api/v1", ""); - return this.webUrl; + else if (projectName !== undefined) { + params.append("name", projectName); } - else if (this.apiUrl.includes("/api") && - !this.apiUrl.split(".", 1)[0].endsWith("api")) { - this.webUrl = this.apiUrl.replace("/api", ""); - return this.webUrl; + else { + throw new Error("Must provide projectName or projectId"); } - else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return this.webUrl; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + try { + const result = await response.json(); + if (!response.ok) { + return false; + } + // If it's OK and we're querying by name, need to check the list is not empty + if (Array.isArray(result)) { + return result.length > 0; + } + // projectId querying + return true; } - else if (this.apiUrl.split(".", 1)[0].includes("eu")) { - this.webUrl = "https://eu.smith.langchain.com"; - return this.webUrl; + catch (e) { + return false; } - else if (this.apiUrl.split(".", 1)[0].includes("beta")) { - this.webUrl = "https://beta.smith.langchain.com"; - return this.webUrl; + } + async readProject({ projectId, projectName, includeStats, }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); } else { - this.webUrl = "https://smith.langchain.com"; - return this.webUrl; + throw new Error("Must provide projectName or projectId"); + } + if (includeStats !== undefined) { + params.append("include_stats", includeStats.toString()); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; + } + else { + result = response; } + return result; } - get headers() { - const headers = { - "User-Agent": `langsmith-js/${__version__}`, - }; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; + async getProjectUrl({ projectId, projectName, }) { + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide either projectName or projectId"); } - return headers; + const project = await this.readProject({ projectId, projectName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; } - async processInputs(inputs) { - if (this.hideInputs === false) { - return inputs; + async getDatasetUrl({ datasetId, datasetName, }) { + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - if (this.hideInputs === true) { - return {}; + const dataset = await this.readDataset({ datasetId, datasetName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + } + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; } - if (typeof this.hideInputs === "function") { - return this.hideInputs(inputs); + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; } - return inputs; + throw new Error("No projects found to resolve tenant."); } - async processOutputs(outputs) { - if (this.hideOutputs === false) { - return outputs; + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, } = {}) { + const params = new URLSearchParams(); + if (projectIds !== undefined) { + for (const projectId of projectIds) { + params.append("id", projectId); + } } - if (this.hideOutputs === true) { - return {}; + if (name !== undefined) { + params.append("name", name); } - if (typeof this.hideOutputs === "function") { - return this.hideOutputs(outputs); + if (nameContains !== undefined) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== undefined) { + params.append("reference_dataset", referenceDatasetId); + } + else if (referenceDatasetName !== undefined) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName, + }); + params.append("reference_dataset", dataset.id); + } + if (referenceFree !== undefined) { + params.append("reference_free", referenceFree.toString()); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; } - return outputs; } - async prepareRunCreateOrUpdateInputs(run) { - const runParams = { ...run }; - if (runParams.inputs !== undefined) { - runParams.inputs = await this.processInputs(runParams.inputs); + async deleteProject({ projectId, projectName, }) { + let projectId_; + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide projectName or projectId"); } - if (runParams.outputs !== undefined) { - runParams.outputs = await this.processOutputs(runParams.outputs); + else if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); } - return runParams; + else if (projectId === undefined) { + projectId_ = (await this.readProject({ projectName })).id; + } + else { + projectId_ = projectId; + } + assertUuid(projectId_); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); } - async _getResponse(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); + } + if (dataType) { + formData.append("data_type", dataType); + } + if (name) { + formData.append("name", name); + } const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "GET", + method: "POST", headers: this.headers, + body: formData, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `Failed to fetch ${path}`); - return response; - } - async _get(path, queryParams) { - const response = await this._getResponse(path, queryParams); - return response.json(); + await raiseForStatus(response, "upload CSV"); + const result = await response.json(); + return result; } - async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { - let offset = Number(queryParams.get("offset")) || 0; - const limit = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset)); - queryParams.set("limit", String(limit)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = transform - ? transform(await response.json()) - : await response.json(); - if (items.length === 0) { - break; - } - yield items; - if (items.length < limit) { - break; - } - offset += items.length; + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { + const body = { + name, + description, + extra: metadata ? { metadata } : undefined, + }; + if (dataType) { + body.data_type = dataType; } - } - async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { - const bodyParams = body ? { ...body } : {}; - while (true) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { - method: requestMethod, - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: JSON.stringify(bodyParams), - }); - const responseBody = await response.json(); - if (!responseBody) { - break; - } - if (!responseBody[dataKey]) { - break; - } - yield responseBody[dataKey]; - const cursors = responseBody.cursors; - if (!cursors) { - break; - } - if (!cursors.next) { - break; - } - bodyParams.cursor = cursors.next; + if (inputsSchema) { + body.inputs_schema_definition = inputsSchema; } - } - // Allows mocking for tests - _shouldSample() { - if (this.tracingSampleRate === undefined) { - return true; + if (outputsSchema) { + body.outputs_schema_definition = outputsSchema; } - return Math.random() < this.tracingSampleRate; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create dataset"); + const result = await response.json(); + return result; } - _filterForSampling(runs, patch = false) { - if (this.tracingSampleRate === undefined) { - return runs; + async readDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + // limit to 1 result + const params = new URLSearchParams({ limit: "1" }); + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - if (patch) { - const sampled = []; - for (const run of runs) { - if (!this.filteredPostUuids.has(run.id)) { - sampled.push(run); - } - else { - this.filteredPostUuids.delete(run.id); - } - } - return sampled; + else if (datasetId !== undefined) { + assertUuid(datasetId); + path += `/${datasetId}`; + } + else if (datasetName !== undefined) { + params.append("name", datasetName); } else { - // For new runs, sample at trace level to maintain consistency - const sampled = []; - for (const run of runs) { - const traceId = run.trace_id ?? run.id; - // If we've already made a decision about this trace, follow it - if (this.filteredPostUuids.has(traceId)) { - continue; - } - // For new traces, apply sampling - if (run.id === traceId) { - if (this._shouldSample()) { - sampled.push(run); - } - else { - this.filteredPostUuids.add(traceId); - } - } - else { - // Child runs follow their trace's sampling decision - sampled.push(run); - } - } - return sampled; + throw new Error("Must provide datasetName or datasetId"); } - } - async _getBatchSizeLimitBytes() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeBytesLimit ?? - serverInfo.batch_ingest_config?.size_limit_bytes ?? - DEFAULT_BATCH_SIZE_LIMIT_BYTES); - } - async _getMultiPartSupport() { - const serverInfo = await this._ensureServerInfo(); - return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); - } - drainAutoBatchQueue(batchSizeLimit) { - const promises = []; - while (this.autoBatchQueue.items.length > 0) { - const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); - if (!batch.length) { - done(); - break; + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); } - const batchPromise = this._processBatch(batch, done).catch(console.error); - promises.push(batchPromise); + result = response[0]; } - return Promise.all(promises); - } - async _processBatch(batch, done) { - if (!batch.length) { - done(); - return; + else { + result = response; } + return result; + } + async hasDataset({ datasetId, datasetName, }) { try { - const ingestParams = { - runCreates: batch - .filter((item) => item.action === "create") - .map((item) => item.item), - runUpdates: batch - .filter((item) => item.action === "update") - .map((item) => item.item), - }; - const serverInfo = await this._ensureServerInfo(); - if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { - await this.multipartIngestRuns(ingestParams); - } - else { - await this.batchIngestRuns(ingestParams); - } + await this.readDataset({ datasetId, datasetName }); + return true; } - finally { - done(); + catch (e) { + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + e instanceof Error && + e.message.toLocaleLowerCase().includes("not found")) { + return false; + } + throw e; } } - async processRunOperation(item) { - clearTimeout(this.autoBatchTimeout); - this.autoBatchTimeout = undefined; - if (item.action === "create") { - item.item = mergeRuntimeEnvIntoRunCreate(item.item); - } - const itemPromise = this.autoBatchQueue.push(item); - if (this.manualFlushMode) { - // Rely on manual flushing in serverless environments - return itemPromise; + async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { + let datasetId_ = datasetId; + if (datasetId_ === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { - void this.drainAutoBatchQueue(sizeLimitBytes); + else if (datasetId_ !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - if (this.autoBatchQueue.items.length > 0) { - this.autoBatchTimeout = setTimeout(() => { - this.autoBatchTimeout = undefined; - void this.drainAutoBatchQueue(sizeLimitBytes); - }, this.autoBatchAggregationDelayMs); + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } - return itemPromise; - } - async _getServerInfo() { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/info`, { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), - ...this.fetchOptions, + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" + ? fromVersion + : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), }); - await raiseForStatus(response, "get server info"); - const json = await response.json(); - if (this.debug) { - console.log("\n=== LangSmith Server Configuration ===\n" + - JSON.stringify(json, null, 2) + - "\n"); - } - return json; + const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + return response; } - async _ensureServerInfo() { - if (this._getServerInfoPromise === undefined) { - this._getServerInfoPromise = (async () => { - if (this._serverInfo === undefined) { - try { - this._serverInfo = await this._getServerInfo(); - } - catch (e) { - console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); - } - } - return this._serverInfo ?? {}; - })(); + async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { + const path = "/datasets"; + if (datasetId !== undefined) { + // do nothing } - return this._getServerInfoPromise.then((serverInfo) => { - if (this._serverInfo === undefined) { - this._getServerInfoPromise = undefined; - } - return serverInfo; + else if (datasetName !== undefined) { + datasetId = (await this.readDataset({ datasetName })).id; + } + else { + throw new Error("Must provide either datasetName or datasetId"); + } + const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); + const datasetText = await response.text(); + const dataset = datasetText + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + return dataset; + } + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString(), }); - } - async _getSettings() { - if (!this.settings) { - this.settings = this._get("/settings"); + if (datasetIds !== undefined) { + for (const id_ of datasetIds) { + params.append("id", id_); + } + } + if (datasetName !== undefined) { + params.append("name", datasetName); + } + if (datasetNameContains !== undefined) { + params.append("name_contains", datasetNameContains); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; } - return await this.settings; } /** - * Flushes current queued traces. + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset */ - async flush() { - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - await this.drainAutoBatchQueue(sizeLimitBytes); - } - async createRun(run) { - if (!this._filterForSampling([run]).length) { - return; - } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const session_name = run.project_name; - delete run.project_name; - const runCreate = await this.prepareRunCreateOrUpdateInputs({ - session_name, - ...run, - start_time: run.start_time ?? Date.now(), - }); - if (this.autoBatchTracing && - runCreate.trace_id !== undefined && - runCreate.dotted_order !== undefined) { - void this.processRunOperation({ - action: "create", - item: runCreate, - }).catch(console.error); - return; + async updateDataset(props) { + const { datasetId, datasetName, ...update } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - const mergedRunCreateParam = mergeRuntimeEnvIntoRunCreate(runCreate); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs`, { - method: "POST", - headers, - body: serialize(mergedRunCreateParam), + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(update), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create run", true); + await raiseForStatus(response, "update dataset"); + return (await response.json()); } /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. */ - async batchIngestRuns({ runCreates, runUpdates, }) { - if (runCreates === undefined && runUpdates === undefined) { - return; + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); - let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag, + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update dataset tags"); + } + async deleteDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - const rawBatch = { - post: preparedCreateParams, - patch: preparedUpdateParams, - }; - if (!rawBatch.post.length && !rawBatch.patch.length) { - return; + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } - const batchChunks = { - post: [], - patch: [], - }; - for (const k of ["post", "patch"]) { - const key = k; - const batchItems = rawBatch[key].reverse(); - let batchItem = batchItems.pop(); - while (batchItem !== undefined) { - // Type is wrong but this is a deprecated code path anyway - batchChunks[key].push(batchItem); - batchItem = batchItems.pop(); - } + if (datasetId_ !== undefined) { + assertUuid(datasetId_); + path += `/${datasetId_}`; } - if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { - await this._postBatchIngestRuns(serialize(batchChunks)); + else { + throw new Error("Must provide datasetName or datasetId"); } + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); } - async _postBatchIngestRuns(body) { - const headers = { - ...this.headers, - "Content-Type": "application/json", - Accept: "application/json", + async indexDataset({ datasetId, datasetName, tag, }) { + let datasetId_ = datasetId; + if (!datasetId_ && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (!datasetId_) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + assertUuid(datasetId_); + const data = { + tag: tag, }; - const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/batch`, { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { method: "POST", - headers, - body: body, + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "batch create run", true); + await raiseForStatus(response, "index dataset"); + await response.json(); } /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs + * Lets you run a similarity search query on a dataset. + * + * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. + * + * @param inputs The input on which to run the similarity search. Must have the + * same schema as the dataset. + * + * @param datasetId The dataset to search for similar examples. + * + * @param limit The maximum number of examples to return. Will return the top `limit` most + * similar examples in order of most similar to least similar. If no similar + * examples are found, random examples will be returned. + * + * @param filter A filter string to apply to the search. Only examples will be returned that + * match the filter string. Some examples of filters + * + * - eq(metadata.mykey, "value") + * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) + * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) + * + * @returns A list of similar examples. + * + * + * @example + * dataset_id = "123e4567-e89b-12d3-a456-426614174000" + * inputs = {"text": "How many people live in Berlin?"} + * limit = 5 + * examples = await client.similarExamples(inputs, dataset_id, limit) */ - async multipartIngestRuns({ runCreates, runUpdates, }) { - if (runCreates === undefined && runUpdates === undefined) { - return; + async similarExamples(inputs, datasetId, limit, { filter, } = {}) { + const data = { + limit: limit, + inputs: inputs, + }; + if (filter !== undefined) { + data["filter"] = filter; } - // transform and convert to dicts - const allAttachments = {}; - let preparedCreateParams = []; - for (const create of runCreates ?? []) { - const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); - if (preparedCreate.id !== undefined && - preparedCreate.attachments !== undefined) { - allAttachments[preparedCreate.id] = preparedCreate.attachments; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "fetch similar examples"); + const result = await response.json(); + return result["examples"]; + } + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== undefined || options !== undefined) { + throw new Error("Cannot provide outputs or options when using ExampleCreate object"); } - delete preparedCreate.attachments; - preparedCreateParams.push(preparedCreate); } - let preparedUpdateParams = []; - for (const update of runUpdates ?? []) { - preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs + ? options?.datasetName + : inputsOrUpdate.dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - // require trace_id and dotted_order - const invalidRunCreate = preparedCreateParams.find((runCreate) => { - return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); - }); - if (invalidRunCreate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { - return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); - }); - if (invalidRunUpdate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; } - // combine post and patch dicts where possible - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) { + data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments, + }; + } + else { + data = inputsOrUpdate; + } + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + const example = await this.readExample(response.example_ids?.[0] ?? v4()); + return example; + } + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) { + return []; } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; + const uploads = propsOrUploads; + let datasetId_ = uploads[0].dataset_id; + const datasetName_ = uploads[0].dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const response = await this._uploadExamplesMultipart(datasetId_, uploads); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; } - if (preparedCreateParams.length === 0 && - preparedUpdateParams.length === 0) { - return; + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; + if (inputs === undefined) { + throw new Error("Must provide inputs when using legacy parameters"); } - // send the runs in multipart requests - const accumulatedContext = []; - const accumulatedParts = []; - for (const [method, payloads] of [ - ["post", preparedCreateParams], - ["patch", preparedUpdateParams], - ]) { - for (const originalPayload of payloads) { - // collect fields to be sent as separate parts - const { inputs, outputs, events, attachments, ...payload } = originalPayload; - const fields = { inputs, outputs, events }; - // encode the main run payload - const stringifiedPayload = serialize(payload); - accumulatedParts.push({ - name: `${method}.${payload.id}`, - payload: new Blob([stringifiedPayload], { - type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip - }), - }); - // encode the fields we collected - for (const [key, value] of Object.entries(fields)) { - if (value === undefined) { - continue; - } - const stringifiedValue = serialize(value); - accumulatedParts.push({ - name: `${method}.${payload.id}.${key}`, - payload: new Blob([stringifiedValue], { - type: `application/json; length=${stringifiedValue.length}`, - }), - }); - } - // encode the attachments - if (payload.id !== undefined) { - const attachments = allAttachments[payload.id]; - if (attachments) { - delete allAttachments[payload.id]; - for (const [name, attachment] of Object.entries(attachments)) { - let contentType; - let content; - if (Array.isArray(attachment)) { - [contentType, content] = attachment; - } - else { - contentType = attachment.mimeType; - content = attachment.data; - } - // Validate that the attachment name doesn't contain a '.' - if (name.includes(".")) { - console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + - `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); - continue; - } - accumulatedParts.push({ - name: `attachment.${payload.id}.${name}`, - payload: new Blob([content], { - type: `${contentType}; length=${content.byteLength}`, - }), - }); - } - } - } - // compute context - accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + let datasetId_ = datasetId; + const datasetName_ = datasetName; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx], + }; + }); + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); + } + return message; + }); + const finalOutput = isLangChainMessage(generations) + ? convertLangChainMessageToExample(generations) + : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const rawExample = await this._get(path); + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type, + }; + return acc; + }, {}); + } + return example; + } + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { + let datasetId_; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId !== undefined) { + datasetId_ = datasetId; + } + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + throw new Error("Must provide a datasetName or datasetId"); + } + const params = new URLSearchParams({ dataset: datasetId_ }); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const inlineS3Urls_ = inlineS3Urls ?? true; + params.append("inline_s3_urls", inlineS3Urls_.toString()); + if (exampleIds !== undefined) { + for (const id_ of exampleIds) { + params.append("id", id_); } } - await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; ")); - } - async _sendMultipartRequest(parts, context) { - try { - // Create multipart form data manually using Blobs - const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); - const chunks = []; - for (const part of parts) { - // Add field boundary - chunks.push(new Blob([`--${boundary}\r\n`])); - chunks.push(new Blob([ - `Content-Disposition: form-data; name="${part.name}"\r\n`, - `Content-Type: ${part.payload.type}\r\n\r\n`, - ])); - chunks.push(part.payload); - chunks.push(new Blob(["\r\n"])); - } - // Add final boundary - chunks.push(new Blob([`--${boundary}--\r\n`])); - // Combine all chunks into a single Blob - const body = new Blob(chunks); - // Convert Blob to ArrayBuffer for compatibility - const arrayBuffer = await body.arrayBuffer(); - const res = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/multipart`, { - method: "POST", - headers: { - ...this.headers, - "Content-Type": `multipart/form-data; boundary=${boundary}`, - }, - body: arrayBuffer, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "ingest multipart runs", true); - // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (splits !== undefined) { + for (const split of splits) { + params.append("splits", split); + } } - catch (e) { - console.warn(`${e.message.trim()}\n\nContext: ${context}`); + if (metadata !== undefined) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); } - } - async updateRun(runId, run) { - assertUuid(runId); - if (run.inputs) { - run.inputs = await this.processInputs(run.inputs); + if (limit !== undefined) { + params.append("limit", limit.toString()); } - if (run.outputs) { - run.outputs = await this.processOutputs(run.outputs); + if (offset !== undefined) { + params.append("offset", offset.toString()); } - // TODO: Untangle types - const data = { ...run, id: runId }; - if (!this._filterForSampling([data], true).length) { - return; + if (filter !== undefined) { + params.append("filter", filter); } - if (this.autoBatchTracing && - data.trace_id !== undefined && - data.dotted_order !== undefined) { - if (run.end_time !== undefined && - data.parent_run_id === undefined && - this.blockOnRootRunFinalization && - !this.manualFlushMode) { - // Trigger batches as soon as a root trace ends and wait to ensure trace finishes - // in serverless environments. - await this.processRunOperation({ action: "update", item: data }).catch(console.error); - return; + if (includeAttachments === true) { + ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + } + let i = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || undefined, + }; + return acc; + }, {}); + } + yield example; + i++; } - else { - void this.processRunOperation({ action: "update", item: data }).catch(console.error); + if (limit !== undefined && i >= limit) { + break; } - return; } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - body: serialize(run), + } + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update run", true); + await raiseForStatus(response, `delete ${path}`); + await response.json(); } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - assertUuid(runId); - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns && run.child_run_ids) { - run = await this._loadChildRuns(run); + async updateExample(exampleIdOrUpdate, update) { + let exampleId; + if (update) { + exampleId = exampleIdOrUpdate; } - return run; - } - async getRunUrl({ runId, run, projectOpts, }) { - if (run !== undefined) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; - } - else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; - } - else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; - } - else { - const project = await this.readProject({ - projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", - }); - sessionId = project.id; - } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; + else { + exampleId = exampleIdOrUpdate.id; } - else if (runId !== undefined) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); - } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; + assertUuid(exampleId); + let updateToUse; + if (update) { + updateToUse = { id: exampleId, ...update }; } else { - throw new Error("Must provide either runId or run"); + updateToUse = exampleIdOrUpdate; + } + let datasetId; + if (updateToUse.dataset_id !== undefined) { + datasetId = updateToUse.dataset_id; + } + else { + const example = await this.readExample(exampleId); + datasetId = example.dataset_id; } + return this._updateExamplesMultipart(datasetId, [updateToUse]); } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ id: run.child_run_ids })); - const treemap = {}; - const runs = {}; - // TODO: make dotted order required when the migration finishes - childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || - childRun.parent_run_id === undefined) { - throw new Error(`Child run ${childRun.id} has no parent`); - } - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; + async updateExamples(update) { + // We will naively get dataset id from first example and assume it works for all + let datasetId; + if (update[0].dataset_id === undefined) { + const example = await this.readExample(update[0].id); + datasetId = example.dataset_id; } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; - } + else { + datasetId = update[0].dataset_id; } - return run; + return this._updateExamplesMultipart(datasetId, update); } /** - * List runs from the LangSmith server. - * @param projectId - The ID of the project to filter by. - * @param projectName - The name of the project to filter by. - * @param parentRunId - The ID of the parent run to filter by. - * @param traceId - The ID of the trace to filter by. - * @param referenceExampleId - The ID of the reference example to filter by. - * @param startTime - The start time to filter by. - * @param isRoot - Indicates whether to only return root runs. - * @param runType - The run type to filter by. - * @param error - Indicates whether to filter by error runs. - * @param id - The ID of the run to filter by. - * @param query - The query string to filter by. - * @param filter - The filter string to apply to the run spans. - * @param traceFilter - The filter string to apply on the root run of the trace. - * @param treeFilter - The filter string to apply on other runs in the trace. - * @param limit - The maximum number of runs to retrieve. - * @returns {AsyncIterable} - The runs. - * - * @example - * // List all runs in a project - * const projectRuns = client.listRuns({ projectName: "" }); - * - * @example - * // List LLM and Chat runs in the last 24 hours - * const todaysLLMRuns = client.listRuns({ - * projectName: "", - * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), - * run_type: "llm", - * }); - * - * @example - * // List traces in a project - * const rootRuns = client.listRuns({ - * projectName: "", - * execution_order: 1, - * }); - * - * @example - * // List runs without errors - * const correctRuns = client.listRuns({ - * projectName: "", - * error: false, - * }); - * - * @example - * // List runs by run ID - * const runIds = [ - * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", - * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", - * ]; - * const selectedRuns = client.listRuns({ run_ids: runIds }); - * - * @example - * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 - * const chainRuns = client.listRuns({ - * projectName: "", - * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', - * }); - * - * @example - * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 - * const goodExtractorRuns = client.listRuns({ - * projectName: "", - * filter: 'eq(name, "extractor")', - * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', - * }); + * Get dataset version by closest date or exact tag. * - * @example - * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 - * const complexRuns = client.listRuns({ - * projectName: "", - * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', - * }); + * Use this to resolve the nearest version to a given timestamp or for a given tag. * - * @example - * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds - * const taggedRuns = client.listRuns({ - * projectName: "", - * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', - * }); + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version */ - async *listRuns(props) { - const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; - let projectIds = []; - if (projectId) { - projectIds = Array.isArray(projectId) ? projectId : [projectId]; + async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { + let resolvedDatasetId; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + resolvedDatasetId = dataset.id; } - if (projectName) { - const projectNames = Array.isArray(projectName) - ? projectName - : [projectName]; - const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); - projectIds.push(...projectIds_); + else { + resolvedDatasetId = datasetId; } - const default_select = [ - "app_path", - "child_run_ids", - "completion_cost", - "completion_tokens", - "dotted_order", - "end_time", - "error", - "events", - "extra", - "feedback_stats", - "first_token_time", - "id", - "inputs", - "name", - "outputs", - "parent_run_id", - "parent_run_ids", - "prompt_cost", - "prompt_tokens", - "reference_example_id", - "run_type", - "session_id", - "start_time", - "status", - "tags", - "total_cost", - "total_tokens", - "trace_id", - ]; - const body = { - session: projectIds.length ? projectIds : null, - run_type: runType, - reference_example: referenceExampleId, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - execution_order: executionOrder, - parent_run: parentRunId, - start_time: startTime ? startTime.toISOString() : null, - error, - id, - limit, - trace: traceId, - select: select ? select : default_select, - is_root: isRoot, - order, + assertUuid(resolvedDatasetId); + if ((asOf && tag) || (!asOf && !tag)) { + throw new Error("Exactly one of asOf and tag must be specified."); + } + const params = new URLSearchParams(); + if (asOf !== undefined) { + params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + } + if (tag !== undefined) { + params.append("tag", tag); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this.headers }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "read dataset version"); + return await response.json(); + } + async listDatasetSplits({ datasetId, datasetName, asOf, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const response = await this._get(`/datasets/${datasetId_}/splits`, params); + return response; + } + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove, }; - let runsYielded = 0; - for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { - if (limit) { - if (runsYielded >= limit) { - break; - } - if (runs.length + runsYielded > limit) { - const newRuns = runs.slice(0, limit - runsYielded); - yield* newRuns; - break; - } - runsYielded += runs.length; - yield* runs; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update dataset splits", true); + } + /** + * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + */ + async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { + warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); + let run_; + if (typeof run === "string") { + run_ = await this.readRun(run, { loadChildRuns }); + } + else if (typeof run === "object" && "id" in run) { + run_ = run; + } + else { + throw new Error(`Invalid run type: ${typeof run}`); + } + if (run_.reference_example_id !== null && + run_.reference_example_id !== undefined) { + referenceExample = await this.readExample(run_.reference_example_id); + } + const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); + const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); + return feedbacks[0]; + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { + if (!runId && !projectId) { + throw new Error("One of runId or projectId must be provided"); + } + if (runId && projectId) { + throw new Error("Only one of runId or projectId can be provided"); + } + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {}, + }; + if (sourceRunId !== undefined && + feedback_source?.metadata !== undefined && + !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + if (feedback_source?.metadata !== undefined && + feedback_source.metadata["__run"]?.run_id !== undefined) { + assertUuid(feedback_source.metadata["__run"].run_id); + } + const feedback = { + id: feedbackId ?? v4(), + run_id: runId, + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source: feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: projectId, + }; + const url = `${this.apiUrl}/feedback`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedback), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create feedback", true); + return feedback; + } + async updateFeedback(feedbackId, { score, value, correction, comment, }) { + const feedbackUpdate = {}; + if (score !== undefined && score !== null) { + feedbackUpdate["score"] = _formatFeedbackScore(score); + } + if (value !== undefined && value !== null) { + feedbackUpdate["value"] = value; + } + if (correction !== undefined && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== undefined && comment !== null) { + feedbackUpdate["comment"] = comment; + } + assertUuid(feedbackId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedbackUpdate), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update feedback", true); + } + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; + } + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + queryParams.append("run", runIds.join(",")); + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); } - else { - yield* runs; + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); } } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; + } } - async *listGroupRuns(props) { - const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; - const sessionId = projectId || (await this.readProject({ projectName })).id; - const baseBody = { - session_id: sessionId, - group_by: groupBy, - filter, - start_time: startTime ? startTime.toISOString() : null, - end_time: endTime ? endTime.toISOString() : null, - limit: Number(limit) || 100, + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { + const body = { + run_id: runId, + feedback_key: feedbackKey, + feedback_config: feedbackConfig, }; - let currentOffset = Number(offset) || 0; - const path = "/runs/group"; - const url = `${this.apiUrl}${path}`; - while (true) { - const currentBody = { - ...baseBody, - offset: currentOffset, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(filteredPayload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = await response.json(); - const { groups, total } = items; - if (groups.length === 0) { - break; - } - for (const thread of groups) { - yield thread; + if (expiration) { + if (typeof expiration === "string") { + body["expires_at"] = expiration; } - currentOffset += groups.length; - if (currentOffset >= total) { - break; + else if (expiration?.hours || expiration?.minutes || expiration?.days) { + body["expires_in"] = expiration; } } - } - async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { - let projectIds_ = projectIds || []; - if (projectNames) { - projectIds_ = [ - ...(projectIds || []), - ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), - ]; + else { + body["expires_in"] = { + hours: 3, + }; } - const payload = { - id, - trace, - parent_run: parentRun, - run_type: runType, - session: projectIds_, - reference_example: referenceExampleIds, - start_time: startTime, - end_time: endTime, - error, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - is_root: isRoot, - data_source_type: dataSourceType, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { method: "POST", - headers: this.headers, - body: JSON.stringify(filteredPayload), + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); const result = await response.json(); return result; } - async shareRun(runId, { shareId } = {}) { - const data = { - run_id: runId, - share_token: shareId || v4(), + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { + if (experimentIds.length === 0) { + throw new Error("At least one experiment is required"); + } + if (!referenceDatasetId) { + referenceDatasetId = (await this.readProject({ + projectId: experimentIds[0], + })).reference_dataset_id; + } + if (!referenceDatasetId == null) { + throw new Error("A reference dataset is required"); + } + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? new Date())?.toISOString(), + extra: {}, }; - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), + if (metadata) + body.extra["metadata"] = metadata; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + return await response.json(); } - async unshareRun(runId) { + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "unshare run", true); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) { + yield* tokens; + } } - async readRunSharedLink(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return undefined; + _selectEvalResults(results) { + let results_; + if ("results" in results) { + results_ = results.results; } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + else if (Array.isArray(results)) { + results_ = results; + } + else { + results_ = [results]; + } + return results_; } - async listSharedRuns(shareToken, { runIds, } = {}) { - const queryParams = new URLSearchParams({ - share_token: shareToken, - }); - if (runIds !== undefined) { - for (const runId of runIds) { - queryParams.append("id", runId); + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) { + sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; + } + let runId_ = null; + if (res.targetRunId) { + runId_ = res.targetRunId; + } + else if (run) { + runId_ = run.id; } + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model", + })); } - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { - method: "GET", - headers: this.headers, + return [evalResults, feedbacks]; + } + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) { + queueIds.forEach((id, i) => { + assertUuid(id, `queueIds[${i}]`); + params.append("ids", id); + }); + } + if (name) + params.append("name", name); + if (nameContains) + params.append("name_contains", nameContains); + params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count++; + if (limit !== undefined && count >= limit) + break; + } + } + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions } = options; + const body = { + name, + description, + id: queueId || v4(), + rubric_instructions: rubricInstructions, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const runs = await response.json(); - return runs; + await raiseForStatus(response, "create annotation queue"); + const data = await response.json(); + return data; } - async readDatasetSharedSchema(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; + await raiseForStatus(response, "read annotation queue"); + const data = await response.json(); + return data; } - async shareDataset(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - const data = { - dataset_id: datasetId, - }; - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions } = options; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + name, + description, + rubric_instructions: rubricInstructions, + }), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; + await raiseForStatus(response, "update annotation queue"); } - async unshareDataset(datasetId) { - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + /** + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete + */ + async deleteAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { method: "DELETE", - headers: this.headers, + headers: { ...this.headers, Accept: "application/json" }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "unshare dataset", true); + await raiseForStatus(response, "delete annotation queue"); } - async readSharedDataset(shareToken) { - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { - method: "GET", - headers: this.headers, + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const dataset = await response.json(); - return dataset; + await raiseForStatus(response, "add runs to annotation queue"); } /** - * Get shared examples. - * - * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. - * @param {Object} [options] Additional options for listing the examples. - * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. - * @returns {Promise} The shared examples. + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors */ - async listSharedExamples(shareToken, options) { - const params = {}; - if (options?.exampleIds) { - params.id = options.exampleIds; - } - const urlParams = new URLSearchParams(); - Object.entries(params).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((v) => urlParams.append(key, v)); - } - else { - urlParams.append(key, value); - } - }); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + async getRunFromAnnotationQueue(queueId, index) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index}`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const result = await response.json(); - if (!response.ok) { - if ("detail" in result) { - throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${result.detail.join("\n")}`); - } - throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); - } - return result.map((example) => ({ - ...example, - _hostUrl: this.getHostUrl(), - })); + await raiseForStatus(response, "get run from annotation queue"); + return await response.json(); } - async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const extra = projectExtra || {}; - if (metadata) { - extra["metadata"] = metadata; - } - const body = { - name: projectName, - extra, - description, - }; - if (referenceDatasetId !== null) { - body["reference_dataset_id"] = referenceDatasetId; - } - const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create project"); - const result = await response.json(); - return result; + await raiseForStatus(response, "delete run from annotation queue"); } - async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { - const endpoint = `${this.apiUrl}/sessions/${projectId}`; - let extra = projectExtra; - if (metadata) { - extra = { ...(extra || {}), metadata }; - } - const body = { - name, - extra, - description, - end_time: endTime ? new Date(endTime).toISOString() : null, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "get size from annotation queue"); + return await response.json(); + } + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return new Error(`Cannot ${action} for another tenant.\n + Current tenant: ${settings.tenant_handle}\n + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + method: "GET", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update project"); - const result = await response.json(); - return result; - } - async hasProject({ projectId, projectName, }) { - // TODO: Add a head request - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); + const json = await res.json(); + if (!res.ok) { + const detail = typeof json.detail === "string" + ? json.detail + : JSON.stringify(json.detail); + const error = new Error(`Error ${res.status}: ${res.statusText}\n${detail}`); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.statusCode = res.status; + throw error; } - else { - throw new Error("Must provide projectName or projectId"); + if (json.commits.length === 0) { + return undefined; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { - method: "GET", - headers: this.headers, + return json.commits[0].commit_hash; + } + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + body: JSON.stringify({ like: like }), + headers: { ...this.headers, "Content-Type": "application/json" }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - try { - const result = await response.json(); - if (!response.ok) { - return false; + await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); + return await response.json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + if (commitHash !== "latest") { + return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; } - // If it's OK and we're querying by name, need to check the list is not empty - if (Array.isArray(result)) { - return result.length > 0; + else { + return `${this.getHostUrl()}/hub/${owner}/${promptName}`; } - // projectId querying - return true; - } - catch (e) { - return false; - } - } - async readProject({ projectId, projectName, includeStats, }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); } else { - throw new Error("Must provide projectName or projectId"); - } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + const settings = await this._getSettings(); + if (commitHash !== "latest") { + return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + } + else { + return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; } - result = response[0]; - } - else { - result = response; } - return result; } - async getProjectUrl({ projectId, projectName, }) { - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide either projectName or projectId"); - } - const project = await this.readProject({ projectId, projectName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + async promptExists(promptIdentifier) { + const prompt = await this.getPrompt(promptIdentifier); + return !!prompt; } - async getDatasetUrl({ datasetId, datasetName, }) { - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - const dataset = await this.readDataset({ datasetId, datasetName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + async *listCommits(promptOwnerAndName) { + for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { + yield* commits; } - throw new Error("No projects found to resolve tenant."); } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, } = {}) { + async *listPrompts(options) { const params = new URLSearchParams(); - if (projectIds !== undefined) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== undefined) { - params.append("name", name); - } - if (nameContains !== undefined) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== undefined) { - params.append("reference_dataset", referenceDatasetId); - } - else if (referenceDatasetName !== undefined) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName, - }); - params.append("reference_dataset", dataset.id); - } - if (referenceFree !== undefined) { - params.append("reference_free", referenceFree.toString()); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== undefined) { + params.append("is_public", options.isPublic.toString()); } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); + if (options?.query) { + params.append("query", options.query); } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { + yield* prompts; } } - async deleteProject({ projectId, projectName, }) { - let projectId_; - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide projectName or projectId"); - } - else if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId === undefined) { - projectId_ = (await this.readProject({ projectName })).id; - } - else { - projectId_ = projectId; - } - assertUuid(projectId_); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", + async getPrompt(promptIdentifier) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); - } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); - }); - if (description) { - formData.append("description", description); + if (response.status === 404) { + return null; } - if (dataType) { - formData.append("data_type", dataType); + await raiseForStatus(response, "get prompt"); + const result = await response.json(); + if (result.repo) { + return result.repo; } - if (name) { - formData.append("name", name); + else { + return null; } - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + } + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) { + throw new Error(`Cannot create a public prompt without first\n + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at:\n + https://smith.langchain.com/prompts`); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("create a prompt", owner); + } + const data = { + repo_handle: promptName, + ...(options?.description && { description: options.description }), + ...(options?.readme && { readme: options.readme }), + ...(options?.tags && { tags: options.tags }), + is_public: !!options?.isPublic, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { method: "POST", - headers: this.headers, - body: formData, + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "upload CSV"); - const result = await response.json(); - return result; + await raiseForStatus(response, "create prompt"); + const { repo } = await response.json(); + return repo; } - async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { - const body = { - name, - description, - extra: metadata ? { metadata } : undefined, - }; - if (dataType) { - body.data_type = dataType; - } - if (inputsSchema) { - body.inputs_schema_definition = inputsSchema; - } - if (outputsSchema) { - body.outputs_schema_definition = outputsSchema; + async createCommit(promptIdentifier, object, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash + ? await this._getLatestCommitHash(`${owner}/${promptName}`) + : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), + body: JSON.stringify(payload), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create dataset"); + await raiseForStatus(response, "create commit"); const result = await response.json(); - return result; + return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); } - async readDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - // limit to 1 result - const params = new URLSearchParams({ limit: "1" }); - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - assertUuid(datasetId); - path += `/${datasetId}`; - } - else if (datasetName !== undefined) { - params.append("name", datasetName); - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); - } - result = response[0]; - } - else { - result = response; - } - return result; + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); } - async hasDataset({ datasetId, datasetName, }) { - try { - await this.readDataset({ datasetId, datasetName }); - return true; + async _updateExamplesMultipart(datasetId, updates = []) { + if (!(await this._getMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); } - catch (e) { - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - e instanceof Error && - e.message.toLocaleLowerCase().includes("not found")) { - return false; + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + // Prepare the main example body + const exampleBody = { + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { + type: "application/json", + }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); } - throw e; - } - } - async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { - let datasetId_ = datasetId; - if (datasetId_ === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; } - const urlParams = new URLSearchParams({ - from_version: typeof fromVersion === "string" - ? fromVersion - : fromVersion.toISOString(), - to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetIdToUse}/examples`, { + method: "PATCH", + headers: this.headers, + body: formData, }); - const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); - return response; + const result = await response.json(); + return result; } - async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { - const path = "/datasets"; - if (datasetId !== undefined) { - // do nothing - } - else if (datasetName !== undefined) { - datasetId = (await this.readDataset({ datasetName })).id; - } - else { - throw new Error("Must provide either datasetName or datasetId"); - } - const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); - const datasetText = await response.text(); - const dataset = datasetText - .trim() - .split("\n") - .map((line) => JSON.parse(line)); - return dataset; + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); } - async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit.toString(), - offset: offset.toString(), - }); - if (datasetIds !== undefined) { - for (const id_ of datasetIds) { - params.append("id", id_); - } - } - if (datasetName !== undefined) { - params.append("name", datasetName); + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!(await this._getMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); } - if (datasetNameContains !== undefined) { - params.append("name_contains", datasetNameContains); + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4()).toString(); + // Prepare the main example body + const exampleBody = { + created_at: example.created_at, + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + ...(example.source_run_id && { source_run_id: example.source_run_id }), + ...(example.use_source_run_io && { + use_source_run_io: example.use_source_run_io, + }), + ...(example.use_source_run_attachments && { + use_source_run_attachments: example.use_source_run_attachments, + }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, { + method: "POST", + headers: this.headers, + body: formData, + }); + await raiseForStatus(response, "upload examples"); + const result = await response.json(); + return result; + } + async updatePrompt(promptIdentifier, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; + const [owner, promptName] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("update a prompt", owner); } - } - /** - * Update a dataset - * @param props The dataset details to update - * @returns The updated dataset - */ - async updateDataset(props) { - const { datasetId, datasetName, ...update } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + const payload = {}; + if (options?.description !== undefined) + payload.description = options.description; + if (options?.readme !== undefined) + payload.readme = options.readme; + if (options?.tags !== undefined) + payload.tags = options.tags; + if (options?.isPublic !== undefined) + payload.is_public = options.isPublic; + if (options?.isArchived !== undefined) + payload.is_archived = options.isArchived; + // Check if payload is empty + if (Object.keys(payload).length === 0) { + throw new Error("No valid update options provided"); } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update), + body: JSON.stringify(payload), + headers: { + ...this.headers, + "Content-Type": "application/json", + }, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update dataset"); - return (await response.json()); + await raiseForStatus(response, "update prompt"); + return response.json(); } - /** - * Updates a tag on a dataset. - * - * If the tag is already assigned to a different version of this dataset, - * the tag will be moved to the new version. The as_of parameter is used to - * determine which version of the dataset to apply the new tags to. - * - * It must be an exact version of the dataset to succeed. You can - * use the "readDatasetVersion" method to find the exact version - * to apply the tags to. - * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. - * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. - * @param params.asOf The timestamp of the dataset to apply the new tags to. - * @param params.tag The new tag to apply to the dataset. - */ - async updateDatasetTag(props) { - const { datasetId, datasetName, asOf, tag } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + async deletePrompt(promptIdentifier) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), - tag, - }), + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("delete a prompt", owner); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update dataset tags"); + return await response.json(); } - async deleteDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - if (datasetId_ !== undefined) { - assertUuid(datasetId_); - path += `/${datasetId_}`; - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", + async pullPromptCommit(promptIdentifier, options) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + await raiseForStatus(response, "pull prompt commit"); + const result = await response.json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples, + }; } - async indexDataset({ datasetId, datasetName, tag, }) { - let datasetId_ = datasetId; - if (!datasetId_ && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel, + }); + const prompt = JSON.stringify(promptObject.manifest); + return prompt; + } + async pushPrompt(promptIdentifier, options) { + // Create or update prompt metadata + if (await this.promptExists(promptIdentifier)) { + if (options && Object.keys(options).some((key) => key !== "object")) { + await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); + } } - else if (datasetId_ && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); + else { + await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); } - else if (!datasetId_) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + if (!options?.object) { + return await this._getPromptUrl(promptIdentifier); } - assertUuid(datasetId_); - const data = { - tag: tag, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + // Create a commit with the new manifest + const url = await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash, }); - await raiseForStatus(response, "index dataset"); - await response.json(); + return url; } /** - * Lets you run a similarity search query on a dataset. - * - * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. - * - * @param inputs The input on which to run the similarity search. Must have the - * same schema as the dataset. - * - * @param datasetId The dataset to search for similar examples. - * - * @param limit The maximum number of examples to return. Will return the top `limit` most - * similar examples in order of most similar to least similar. If no similar - * examples are found, random examples will be returned. - * - * @param filter A filter string to apply to the search. Only examples will be returned that - * match the filter string. Some examples of filters - * - * - eq(metadata.mykey, "value") - * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) - * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) - * - * @returns A list of similar examples. - * - * - * @example - * dataset_id = "123e4567-e89b-12d3-a456-426614174000" - * inputs = {"text": "How many people live in Berlin?"} - * limit = 5 - * examples = await client.similarExamples(inputs, dataset_id, limit) + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} */ - async similarExamples(inputs, datasetId, limit, { filter, } = {}) { - const data = { - limit: limit, - inputs: inputs, - }; - if (filter !== undefined) { - data["filter"] = filter; - } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new Client({ + apiUrl: parsedApiUrl, + // Placeholder API key not needed anymore in most cases, but + // some private deployments may have API key-based rate limiting + // that would cause this to fail if we provide no value. + apiKey: "placeholder", }); - await raiseForStatus(response, "fetch similar examples"); - const result = await response.json(); - return result["examples"]; - } - async createExample(inputsOrUpdate, outputs, options) { - if (isExampleCreate(inputsOrUpdate)) { - if (outputs !== undefined || options !== undefined) { - throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; } } - let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; - const datasetName_ = outputs - ? options?.datasetName - : inputsOrUpdate.dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); + catch (_) { + // `.hasDataset` will throw an error if the dataset does not exist. + // no-op in that case } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + // Fetch examples first, then create the dataset + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? undefined, + outputsSchema: ds.outputs_schema_definition ?? undefined, + }); + try { + await this.createExamples({ + inputs: examples.map((e) => e.inputs), + outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), + datasetId: dataset.id, + }); } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + catch (e) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + + "You should delete it manually."); + throw e; } - const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); - let data; - if (!isExampleCreate(inputsOrUpdate)) { - data = { - inputs: inputsOrUpdate, - outputs, - created_at: createdAt_?.toISOString(), - id: options?.exampleId, - metadata: options?.metadata, - split: options?.split, - source_run_id: options?.sourceRunId, - use_source_run_io: options?.useSourceRunIO, - use_source_run_attachments: options?.useSourceRunAttachments, - attachments: options?.attachments, - }; + } + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + // Try parsing as UUID + try { + assertUuid(urlOrToken); // Will throw if it's not a UUID. + return [apiUrl, urlOrToken]; } - else { - data = inputsOrUpdate; + catch (_) { + // no-op if it's not a uuid } - const response = await this._uploadExamplesMultipart(datasetId_, [data]); - const example = await this.readExample(response.example_ids?.[0] ?? v4()); - return example; - } - async createExamples(propsOrUploads) { - if (Array.isArray(propsOrUploads)) { - if (propsOrUploads.length === 0) { - return []; - } - const uploads = propsOrUploads; - let datasetId_ = uploads[0].dataset_id; - const datasetName_ = uploads[0].dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + // Parse as URL + try { + const parsedUrl = new URL(urlOrToken); + const pathParts = parsedUrl.pathname + .split("/") + .filter((part) => part !== ""); + if (pathParts.length >= numParts) { + const tokenUuid = pathParts[pathParts.length - numParts]; + return [apiUrl, tokenUuid]; } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + else { + throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); } - const response = await this._uploadExamplesMultipart(datasetId_, uploads); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; - if (inputs === undefined) { - throw new Error("Must provide inputs when using legacy parameters"); } - let datasetId_ = datasetId; - const datasetName_ = datasetName; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); + catch (error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + } + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + return Promise.all([ + ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), + this.batchIngestCaller.queue.onIdle(), + ]); + } +} +function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js + + + +// Update using yarn bump-version +const __version__ = "0.3.31"; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js +// Inlined from https://github.com/flexdinesh/browser-or-node + +let globalEnv; +const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !isDeno(); +const getEnv = () => { + if (globalEnv) { + return globalEnv; + } + if (isBrowser()) { + globalEnv = "browser"; + } + else if (isNode()) { + globalEnv = "node"; + } + else if (isWebWorker()) { + globalEnv = "webworker"; + } + else if (isJsDom()) { + globalEnv = "jsdom"; + } + else if (isDeno()) { + globalEnv = "deno"; + } + else { + globalEnv = "other"; + } + return globalEnv; +}; +let runtimeEnvironment; +function getRuntimeEnvironment() { + if (runtimeEnvironment === undefined) { + const env = getEnv(); + const releaseEnv = getShas(); + runtimeEnvironment = { + library: "langsmith", + runtime: env, + sdk: "langsmith-js", + sdk_version: __version__, + ...releaseEnv, + }; + } + return runtimeEnvironment; +} +/** + * Retrieves the LangChain-specific environment variables from the current runtime environment. + * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security. + * + * @returns {Record} + * - A record of LangChain-specific environment variables. + */ +function getLangChainEnvVars() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + for (const [key, value] of Object.entries(allEnvVars)) { + if (key.startsWith("LANGCHAIN_") && typeof value === "string") { + envVars[key] = value; } - const formattedExamples = inputs.map((input, idx) => { - return { - dataset_id: datasetId_, - inputs: input, - outputs: outputs?.[idx], - metadata: metadata?.[idx], - split: splits?.[idx], - id: exampleIds?.[idx], - attachments: attachments?.[idx], - source_run_id: sourceRunIds?.[idx], - use_source_run_io: useSourceRunIOs?.[idx], - use_source_run_attachments: useSourceRunAttachments?.[idx], - }; - }); - const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); + for (const key in envVars) { + if ((key.toLowerCase().includes("key") || + key.toLowerCase().includes("secret") || + key.toLowerCase().includes("token")) && + typeof envVars[key] === "string") { + const value = envVars[key]; + envVars[key] = + value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); + } } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); + return envVars; +} +/** + * Retrieves the LangChain-specific metadata from the current runtime environment. + * + * @returns {Record} + * - A record of LangChain-specific metadata environment variables. + */ +function getLangChainEnvVarsMetadata() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION", + ]; + for (const [key, value] of Object.entries(allEnvVars)) { + if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && + typeof value === "string" && + !excluded.includes(key) && + !key.toLowerCase().includes("key") && + !key.toLowerCase().includes("secret") && + !key.toLowerCase().includes("token")) { + if (key === "LANGCHAIN_REVISION_ID") { + envVars["revision_id"] = value; } - return message; - }); - const finalOutput = isLangChainMessage(generations) - ? convertLangChainMessageToExample(generations) - : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); + else { + envVars[key] = value; + } + } } - async readExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const rawExample = await this._get(path); - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type, - }; + return envVars; +} +/** + * Retrieves the environment variables from the current runtime environment. + * + * This function is designed to operate in a variety of JS environments, + * including Node.js, Deno, browsers, etc. + * + * @returns {Record | undefined} + * - A record of environment variables if available. + * - `undefined` if the environment does not support or allows access to environment variables. + */ +function getEnvironmentVariables() { + try { + // Check for Node.js environment + // eslint-disable-next-line no-process-env + if (typeof process !== "undefined" && process.env) { + // eslint-disable-next-line no-process-env + return Object.entries(process.env).reduce((acc, [key, value]) => { + acc[key] = String(value); return acc; }, {}); } - return example; + // For browsers and other environments, we may not have direct access to env variables + // Return undefined or any other fallback as required. + return undefined; } - async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { - let datasetId_; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - datasetId_ = datasetId; - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - throw new Error("Must provide a datasetName or datasetId"); - } - const params = new URLSearchParams({ dataset: datasetId_ }); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() + catch (e) { + // Catch any errors that might occur while trying to access environment variables + return undefined; + } +} +function getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/hwchase17/langchainjs/issues/1412 + try { + return typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.[name] : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); + } + catch (e) { + return undefined; + } +} +function getLangSmithEnvironmentVariable(name) { + return (getEnvironmentVariable(`LANGSMITH_${name}`) || + getEnvironmentVariable(`LANGCHAIN_${name}`)); +} +function setEnvironmentVariable(name, value) { + if (typeof process !== "undefined") { + // eslint-disable-next-line no-process-env + process.env[name] = value; + } +} +let cachedCommitSHAs; +/** + * Get the Git commit SHA from common environment variables + * used by different CI/CD platforms. + * @returns {string | undefined} The Git commit SHA or undefined if not found. + */ +function getShas() { + if (cachedCommitSHAs !== undefined) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT", + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = getEnvironmentVariable(env); + if (envVar !== undefined) { + shas[env] = envVar; } - const inlineS3Urls_ = inlineS3Urls ?? true; - params.append("inline_s3_urls", inlineS3Urls_.toString()); - if (exampleIds !== undefined) { - for (const id_ of exampleIds) { - params.append("id", id_); + } + cachedCommitSHAs = shas; + return shas; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js + +const isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== undefined) { + return tracingEnabled; + } + const envVars = ["TRACING_V2", "TRACING"]; + return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js +const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js + + + + + + +function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + // Date only has millisecond precision, so we use the microseconds to break + // possible ties, avoiding incorrect run order + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); +} +/** + * Baggage header information + */ +class Baggage { + constructor(metadata, tags, project_name) { + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + } + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") { + metadata = JSON.parse(value); } - } - if (splits !== undefined) { - for (const split of splits) { - params.append("splits", split); + else if (key === "langsmith-tags") { + tags = value.split(","); + } + else if (key === "langsmith-project") { + project_name = value; } } - if (metadata !== undefined) { - const serializedMetadata = JSON.stringify(metadata); - params.append("metadata", serializedMetadata); + return new Baggage(metadata, tags, project_name); + } + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) { + items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); } - if (limit !== undefined) { - params.append("limit", limit.toString()); + if (this.tags && this.tags.length > 0) { + items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); } - if (offset !== undefined) { - params.append("offset", offset.toString()); + if (this.project_name) { + items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); } - if (filter !== undefined) { - params.append("filter", filter); + return items.join(","); + } +} +class run_trees_RunTree { + constructor(originalConfig) { + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "trace_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "dotted_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Attachments associated with the run. + * Each entry is a tuple of [mime_type, bytes] + */ + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // If you pass in a run tree directly, return a shallow clone + if (run_trees_isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; } - if (includeAttachments === true) { - ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + const defaultConfig = run_trees_RunTree.getDefaultConfig(); + const { metadata, ...config } = originalConfig; + const client = config.client ?? run_trees_RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config?.extra?.metadata, + }; + config.extra = { ...config.extra, metadata: dedupedMetadata }; + Object.assign(this, { ...defaultConfig, ...config, client }); + if (!this.trace_id) { + if (this.parent_run) { + this.trace_id = this.parent_run.trace_id ?? this.id; + } + else { + this.trace_id = this.id; + } } - let i = 0; - for await (const rawExamples of this._getPaginated("/examples", params)) { - for (const rawExample of rawExamples) { - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type || undefined, - }; - return acc; - }, {}); - } - yield example; - i++; + this.execution_order ??= 1; + this.child_execution_order ??= 1; + if (!this.dotted_order) { + const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) { + this.dotted_order = + this.parent_run.dotted_order + "." + currentDottedOrder; } - if (limit !== undefined && i >= limit) { - break; + else { + this.dotted_order = currentDottedOrder; } } } - async deleteExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata, + }, + }; } - async updateExample(exampleIdOrUpdate, update) { - let exampleId; - if (update) { - exampleId = exampleIdOrUpdate; - } - else { - exampleId = exampleIdOrUpdate.id; - } - assertUuid(exampleId); - let updateToUse; - if (update) { - updateToUse = { id: exampleId, ...update }; - } - else { - updateToUse = exampleIdOrUpdate; - } - let datasetId; - if (updateToUse.dataset_id !== undefined) { - datasetId = updateToUse.dataset_id; - } - else { - const example = await this.readExample(exampleId); - datasetId = example.dataset_id; - } - return this._updateExamplesMultipart(datasetId, [updateToUse]); + get metadata() { + return this.extra?.metadata; + } + static getDefaultConfig() { + return { + id: v4(), + run_type: "chain", + project_name: getLangSmithEnvironmentVariable("PROJECT") ?? + getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default", + child_runs: [], + api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time: Date.now(), + serialized: {}, + inputs: {}, + extra: {}, + }; } - async updateExamples(update) { - // We will naively get dataset id from first example and assume it works for all - let datasetId; - if (update[0].dataset_id === undefined) { - const example = await this.readExample(update[0].id); - datasetId = example.dataset_id; - } - else { - datasetId = update[0].dataset_id; + static getSharedClient() { + if (!run_trees_RunTree.sharedClient) { + run_trees_RunTree.sharedClient = new Client(); } - return this._updateExamplesMultipart(datasetId, update); + return run_trees_RunTree.sharedClient; } - /** - * Get dataset version by closest date or exact tag. - * - * Use this to resolve the nearest version to a given timestamp or for a given tag. - * - * @param options The options for getting the dataset version - * @param options.datasetId The ID of the dataset - * @param options.datasetName The name of the dataset - * @param options.asOf The timestamp of the dataset to retrieve - * @param options.tag The tag of the dataset to retrieve - * @returns The dataset version - */ - async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { - let resolvedDatasetId; - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - resolvedDatasetId = dataset.id; - } - else { - resolvedDatasetId = datasetId; + createChild(config) { + const child_execution_order = this.child_execution_order + 1; + const child = new run_trees_RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order: child_execution_order, + }); + // Copy context vars over into the new run tree. + if (_LC_CONTEXT_VARIABLES_KEY in this) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + child[_LC_CONTEXT_VARIABLES_KEY] = + this[_LC_CONTEXT_VARIABLES_KEY]; } - assertUuid(resolvedDatasetId); - if ((asOf && tag) || (!asOf && !tag)) { - throw new Error("Exactly one of asOf and tag must be specified."); + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config.extra?.[LC_CHILD] ?? + this.extra[LC_CHILD]; + // tracing for LangChain is defined by the _parentRunId and runMap of the tracer + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) + ? newConfig.callbacks.copy?.() + : undefined; + if (callbacks) { + // update the parent run id + Object.assign(callbacks, { _parentRunId: child.id }); + // only populate if we're in a newer LC.JS version + callbacks.handlers + ?.find(isLangChainTracerLike) + ?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; } - const params = new URLSearchParams(); - if (asOf !== undefined) { - params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + // propagate child_execution_order upwards + const visited = new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; } - if (tag !== undefined) { - params.append("tag", tag); + this.child_runs.push(child); + return child; + } + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) { + this.extra = this.extra + ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } + : { metadata }; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { - method: "GET", - headers: { ...this.headers }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "read dataset version"); - return await response.json(); } - async listDatasetSplits({ datasetId, datasetName, asOf, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + if (!runExtra.runtime) { + runExtra.runtime = {}; } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + if (runtimeEnv) { + for (const [k, v] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k]) { + runExtra.runtime[k] = v; + } + } } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + parent_run_id = undefined; } else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const params = new URLSearchParams(); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); + parent_run_id = run.parent_run?.id; + child_runs = []; } - const response = await this._get(`/datasets/${datasetId_}/splits`, params); - return response; + const persistedRun = { + id: run.id, + name: run.name, + start_time: run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs: child_runs, + parent_run_id: parent_run_id, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + tags: run.tags, + attachments: run.attachments, + }; + return persistedRun; } - async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); + async postRun(excludeChildRuns = true) { + try { + const runtimeEnv = getRuntimeEnvironment(); + const runCreate = await this._convertToCreate(this, runtimeEnv, true); + await this.client.createRun(runCreate); + if (!excludeChildRuns) { + warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); + } + } } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + } + async patchRun() { + try { + const runUpdate = { + end_time: this.end_time, + error: this.error, + inputs: this.inputs, + outputs: this.outputs, + parent_run_id: this.parent_run?.id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + dotted_order: this.dotted_order, + trace_id: this.trace_id, + tags: this.tags, + attachments: this.attachments, + session_name: this.project_name, + }; + await this.client.updateRun(this.id, runUpdate); } - else { - datasetId_ = datasetId; + catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); } - assertUuid(datasetId_); - const data = { - split_name: splitName, - examples: exampleIds.map((id) => { - assertUuid(id); - return id; - }), - remove, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update dataset splits", true); + } + toJSON() { + return this._convertToCreate(this, undefined, false); } /** - * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + * Add an event to the run tree. + * @param event - A single event or string to add */ - async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { - warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); - let run_; - if (typeof run === "string") { - run_ = await this.readRun(run, { loadChildRuns }); + addEvent(event) { + if (!this.events) { + this.events = []; } - else if (typeof run === "object" && "id" in run) { - run_ = run; + if (typeof event === "string") { + this.events.push({ + name: "event", + time: new Date().toISOString(), + message: event, + }); } else { - throw new Error(`Invalid run type: ${typeof run}`); - } - if (run_.reference_example_id !== null && - run_.reference_example_id !== undefined) { - referenceExample = await this.readExample(run_.reference_example_id); + this.events.push({ + ...event, + time: event.time ?? new Date().toISOString(), + }); } - const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); - const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); - return feedbacks[0]; } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { - if (!runId && !projectId) { - throw new Error("One of runId or projectId must be provided"); - } - if (runId && projectId) { - throw new Error("Only one of runId or projectId can be provided"); - } - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {}, - }; - if (sourceRunId !== undefined && - feedback_source?.metadata !== undefined && - !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; + static fromRunnableConfig(parentConfig, props) { + // We only handle the callback manager case for now + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client; + let tracingEnabled = isTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; } - if (feedback_source?.metadata !== undefined && - feedback_source.metadata["__run"]?.run_id !== undefined) { - assertUuid(feedback_source.metadata["__run"].run_id); + if (!parentRun) { + return new run_trees_RunTree({ + ...props, + client, + tracingEnabled, + project_name: projectName, + }); } - const feedback = { - id: feedbackId ?? v4(), - run_id: runId, - key, - score: _formatFeedbackScore(score), - value, - correction, - comment, - feedback_source: feedback_source, - comparative_experiment_id: comparativeExperimentId, - feedbackConfig, - session_id: projectId, - }; - const url = `${this.apiUrl}/feedback`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedback), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + const parentRunTree = new run_trees_RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client, + tracingEnabled, + project_name: projectName, + tags: [ + ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), + ], + extra: { + metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata, + }, + }, }); - await raiseForStatus(response, "create feedback", true); - return feedback; + return parentRunTree.createChild(props); } - async updateFeedback(feedbackId, { score, value, correction, comment, }) { - const feedbackUpdate = {}; - if (score !== undefined && score !== null) { - feedbackUpdate["score"] = _formatFeedbackScore(score); - } - if (value !== undefined && value !== null) { - feedbackUpdate["value"] = value; + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" + ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage"), + } + : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") + return undefined; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { strTime, time: Date.parse(strTime + "Z"), uuid }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder, + }; + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config.metadata = baggage.metadata; + config.tags = baggage.tags; + config.project_name = baggage.project_name; } - if (correction !== undefined && correction !== null) { - feedbackUpdate["correction"] = correction; + return new run_trees_RunTree(config); + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name).toHeader(), + }; + if (headers) { + for (const [key, value] of Object.entries(result)) { + headers.set(key, value); + } } - if (comment !== undefined && comment !== null) { - feedbackUpdate["comment"] = comment; + return result; + } +} +Object.defineProperty(run_trees_RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null +}); +function run_trees_isRunTree(x) { + return (x !== undefined && + typeof x.createChild === "function" && + typeof x.postRun === "function"); +} +function isLangChainTracerLike(x) { + return (typeof x === "object" && + x != null && + typeof x.name === "string" && + x.name === "langchain_tracer"); +} +function containsLangChainTracerLike(x) { + return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); +} +function isCallbackManagerLike(x) { + return (typeof x === "object" && + x != null && + Array.isArray(x.handlers)); +} +function isRunnableConfigLike(x) { + // Check that it's an object with a callbacks arg + // that has either a CallbackManagerLike object with a langchain tracer within it + // or an array with a LangChainTracerLike object within it + return (x !== undefined && + typeof x.callbacks === "object" && + // Callback manager with a langchain tracer + (containsLangChainTracerLike(x.callbacks?.handlers) || + // Or it's an array with a LangChainTracerLike object within it + containsLangChainTracerLike(x.callbacks))); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js + +class MockAsyncLocalStorage { + getStore() { + return undefined; + } + run(_, callback) { + return callback(); + } +} +const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const mockAsyncLocalStorage = new MockAsyncLocalStorage(); +class AsyncLocalStorageProvider { + getInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; + } + initializeGlobalInstance(instance) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[TRACING_ALS_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[TRACING_ALS_KEY] = instance; } - assertUuid(feedbackId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedbackUpdate), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update feedback", true); } - async readFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; +} +const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); +function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); + if (!permitAbsentRunTree && !run_trees_isRunTree(runTree)) { + throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); + } + return runTree; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function withRunTree(runTree, fn) { + const storage = AsyncLocalStorageProviderSingleton.getInstance(); + return new Promise((resolve, reject) => { + storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); + }); +} +const ROOT = Symbol.for("langsmith:traceable:root"); +function isTraceableFunction(x +// eslint-disable-next-line @typescript-eslint/no-explicit-any +) { + return typeof x === "function" && "langsmith:traceable" in x; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */ +const _hasOwnProperty = Object.prototype.hasOwnProperty; +function helpers_hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys = new Array(obj.length); + for (let k = 0; k < keys.length; k++) { + keys[k] = "" + k; + } + return keys; } - async deleteFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + if (Object.keys) { + return Object.keys(obj); } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - queryParams.append("run", runIds.join(",")); - } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); - } - } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); - } + let keys = []; + for (let i in obj) { + if (helpers_hasOwnProperty(obj, i)) { + keys.push(i); } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; + } + return keys; +} +/** + * Deeply clone the object. + * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) + * @param {any} obj value to clone + * @return {any} cloned obj + */ +function helpers_deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; //this is how JSON.stringify behaves for array items + default: + return obj; //no need to clone primitives + } +} +//3x faster than cached /^\d+$/.test(str) +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; } + return false; } - /** - * Creates a presigned feedback token and URL. - * - * The token can be used to authorize feedback metrics without - * needing an API key. This is useful for giving browser-based - * applications the ability to submit feedback without needing - * to expose an API key. - * - * @param runId The ID of the run. - * @param feedbackKey The feedback key. - * @param options Additional options for the token. - * @param options.expiration The expiration time for the token. - * - * @returns A promise that resolves to a FeedbackIngestToken. - */ - async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { - const body = { - run_id: runId, - feedback_key: feedbackKey, - feedback_config: feedbackConfig, - }; - if (expiration) { - if (typeof expiration === "string") { - body["expires_at"] = expiration; + return true; +} +/** + * Escapes a json pointer path + * @param path The raw pointer + * @return the Escaped path + */ +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) + return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +/** + * Unescapes a json pointer path + * @param path The escaped pointer + * @return The unescaped path + */ +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +function _getPathRecursive(root, obj) { + let found; + for (let key in root) { + if (helpers_hasOwnProperty(root, key)) { + if (root[key] === obj) { + return escapePathComponent(key) + "/"; } - else if (expiration?.hours || expiration?.minutes || expiration?.days) { - body["expires_in"] = expiration; + else if (typeof root[key] === "object") { + found = _getPathRecursive(root[key], obj); + if (found != "") { + return escapePathComponent(key) + "/" + found; + } } } - else { - body["expires_in"] = { - hours: 3, - }; - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const result = await response.json(); - return result; } - async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { - if (experimentIds.length === 0) { - throw new Error("At least one experiment is required"); - } - if (!referenceDatasetId) { - referenceDatasetId = (await this.readProject({ - projectId: experimentIds[0], - })).reference_dataset_id; - } - if (!referenceDatasetId == null) { - throw new Error("A reference dataset is required"); - } - const body = { - id, - name, - experiment_ids: experimentIds, - reference_dataset_id: referenceDatasetId, - description, - created_at: (createdAt ?? new Date())?.toISOString(), - extra: {}, - }; - if (metadata) - body.extra["metadata"] = metadata; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - return await response.json(); + return ""; +} +function getPath(root, obj) { + if (root === obj) { + return "/"; } - /** - * Retrieves a list of presigned feedback tokens for a given run ID. - * @param runId The ID of the run. - * @returns An async iterable of FeedbackIngestToken objects. - */ - async *listPresignedFeedbackTokens(runId) { - assertUuid(runId); - const params = new URLSearchParams({ run_id: runId }); - for await (const tokens of this._getPaginated("/feedback/tokens", params)) { - yield* tokens; - } + const path = _getPathRecursive(root, obj); + if (path === "") { + throw new Error("Object not found in root"); } - _selectEvalResults(results) { - let results_; - if ("results" in results) { - results_ = results.results; - } - else if (Array.isArray(results)) { - results_ = results; - } - else { - results_ = [results]; - } - return results_; + return `/${path}`; +} +/** + * Recursively checks whether an object has any undefined values inside. + */ +function hasUndefined(obj) { + if (obj === undefined) { + return true; } - async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const evalResults = this._selectEvalResults(evaluatorResponse); - const feedbacks = []; - for (const res of evalResults) { - let sourceInfo_ = sourceInfo || {}; - if (res.evaluatorInfo) { - sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; - } - let runId_ = null; - if (res.targetRunId) { - runId_ = res.targetRunId; + if (obj) { + if (Array.isArray(obj)) { + for (let i = 0, len = obj.length; i < len; i++) { + if (hasUndefined(obj[i])) { + return true; + } } - else if (run) { - runId_ = run.id; + } + else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) { + if (hasUndefined(obj[objKeys[i]])) { + return true; + } } - feedbacks.push(await this.createFeedback(runId_, res.key, { - score: res.score, - value: res.value, - comment: res.comment, - correction: res.correction, - sourceInfo: sourceInfo_, - sourceRunId: res.sourceRunId, - feedbackConfig: res.feedbackConfig, - feedbackSourceType: "model", - })); } - return [evalResults, feedbacks]; - } - async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); - return results; } - /** - * API for managing annotation queues - */ - /** - * List the annotation queues on the LangSmith API. - * @param options - The options for listing annotation queues - * @param options.queueIds - The IDs of the queues to filter by - * @param options.name - The name of the queue to filter by - * @param options.nameContains - The substring that the queue name should contain - * @param options.limit - The maximum number of queues to return - * @returns An iterator of AnnotationQueue objects - */ - async *listAnnotationQueues(options = {}) { - const { queueIds, name, nameContains, limit } = options; - const params = new URLSearchParams(); - if (queueIds) { - queueIds.forEach((id, i) => { - assertUuid(id, `queueIds[${i}]`); - params.append("ids", id); - }); - } - if (name) - params.append("name", name); - if (nameContains) - params.append("name_contains", nameContains); - params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); - let count = 0; - for await (const queues of this._getPaginated("/annotation-queues", params)) { - yield* queues; - count++; - if (limit !== undefined && count >= limit) - break; + return false; +} +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" + ? JSON.stringify(args[key], null, 2) + : args[key]; // pretty print + if (typeof value !== "undefined") { + messageParts.push(`${key}: ${value}`); } } - /** - * Create an annotation queue on the LangSmith API. - * @param options - The options for creating an annotation queue - * @param options.name - The name of the annotation queue - * @param options.description - The description of the annotation queue - * @param options.queueId - The ID of the annotation queue - * @returns The created AnnotationQueue object - */ - async createAnnotationQueue(options) { - const { name, description, queueId, rubricInstructions } = options; - const body = { - name, - description, - id: queueId || v4(), - rubric_instructions: rubricInstructions, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "create annotation queue"); - const data = await response.json(); - return data; - } - /** - * Read an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to read - * @returns The AnnotationQueueWithDetails object - */ - async readAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "read annotation queue"); - const data = await response.json(); - return data; - } - /** - * Update an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to update - * @param options - The options for updating the annotation queue - * @param options.name - The new name for the annotation queue - * @param options.description - The new description for the annotation queue - */ - async updateAnnotationQueue(queueId, options) { - const { name, description, rubricInstructions } = options; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - name, - description, - rubric_instructions: rubricInstructions, - }), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update annotation queue"); - } - /** - * Delete an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to delete - */ - async deleteAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + return messageParts.join("\n"); +} +class PatchError extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { name, index, operation, tree })); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: name }); - await raiseForStatus(response, "delete annotation queue"); - } - /** - * Add runs to an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue - * @param runIds - The IDs of the runs to be added to the annotation queue - */ - async addRunsToAnnotationQueue(queueId, runIds) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.defineProperty(this, "index", { + enumerable: true, + configurable: true, + writable: true, + value: index }); - await raiseForStatus(response, "add runs to annotation queue"); - } - /** - * Get a run from an annotation queue at the specified index. - * @param queueId - The ID of the annotation queue - * @param index - The index of the run to retrieve - * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object - * @throws {Error} If the run is not found at the given index or for other API-related errors - */ - async getRunFromAnnotationQueue(queueId, index) { - const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: operation }); - await raiseForStatus(response, "get run from annotation queue"); - return await response.json(); - } - /** - * Delete a run from an an annotation queue. - * @param queueId - The ID of the annotation queue to delete the run from - * @param queueRunId - The ID of the run to delete from the annotation queue - */ - async deleteRunFromAnnotationQueue(queueId, queueRunId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.defineProperty(this, "tree", { + enumerable: true, + configurable: true, + writable: true, + value: tree }); - await raiseForStatus(response, "delete run from annotation queue"); - } - /** - * Get the size of an annotation queue. - * @param queueId - The ID of the annotation queue - */ - async getSizeFromAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree, }); - await raiseForStatus(response, "get size from annotation queue"); - return await response.json(); - } - async _currentTenantIsOwner(owner) { - const settings = await this._getSettings(); - return owner == "-" || settings.tenant_handle === owner; - } - async _ownerConflictError(action, owner) { - const settings = await this._getSettings(); - return new Error(`Cannot ${action} for another tenant.\n - Current tenant: ${settings.tenant_handle}\n - Requested tenant: ${owner}`); } - async _getLatestCommitHash(promptOwnerAndName) { - const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +// @ts-nocheck + +const JsonPatchError = PatchError; +const deepClone = helpers_deepClone; +/* We use a Javascript hash to store each + function. Each hash entry (property) uses + the operation identifiers specified in rfc6902. + In this way, we can map each patch operation + to its dedicated function in efficient way. + */ +/* The operations applicable to an object */ +const objOps = { + add: function (obj, key, document) { + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function (obj, key, document) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document, removed }; + }, + replace: function (obj, key, document) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document, removed }; + }, + move: function (obj, key, document) { + /* in case move target overwrites an existing value, + return the removed value, this can be taxing performance-wise, + and is potentially unneeded */ + let removed = getValueByPointer(document, this.path); + if (removed) { + removed = helpers_deepClone(removed); + } + const originalValue = applyOperation(document, { + op: "remove", + path: this.from, + }).removed; + applyOperation(document, { + op: "add", + path: this.path, + value: originalValue, }); - const json = await res.json(); - if (!res.ok) { - const detail = typeof json.detail === "string" - ? json.detail - : JSON.stringify(json.detail); - const error = new Error(`Error ${res.status}: ${res.statusText}\n${detail}`); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error.statusCode = res.status; - throw error; + return { newDocument: document, removed }; + }, + copy: function (obj, key, document) { + const valueToCopy = getValueByPointer(document, this.from); + // enforce copy by value so further operations don't affect source (see issue #177) + applyOperation(document, { + op: "add", + path: this.path, + value: helpers_deepClone(valueToCopy), + }); + return { newDocument: document }; + }, + test: function (obj, key, document) { + return { newDocument: document, test: _areEquals(obj[key], this.value) }; + }, + _get: function (obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + }, +}; +/* The operations applicable to an array. Many are the same as for the object */ +var arrOps = { + add: function (arr, i, document) { + if (isInteger(i)) { + arr.splice(i, 0, this.value); } - if (json.commits.length === 0) { - return undefined; + else { + // array props + arr[i] = this.value; } - return json.commits[0].commit_hash; - } - async _likeOrUnlikePrompt(promptIdentifier, like) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { - method: "POST", - body: JSON.stringify({ like: like }), - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); - return await response.json(); + // this may be needed when using '-' in an array + return { newDocument: document, index: i }; + }, + remove: function (arr, i, document) { + var removedList = arr.splice(i, 1); + return { newDocument: document, removed: removedList[0] }; + }, + replace: function (arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { newDocument: document, removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get, +}; +/** + * Retrieves a value from a JSON document by a JSON pointer. + * Returns the value. + * + * @param document The document to get the value from + * @param pointer an escaped JSON pointer + * @return The retrieved value + */ +function getValueByPointer(document, pointer) { + if (pointer == "") { + return document; } - async _getPromptUrl(promptIdentifier) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - if (commitHash !== "latest") { - return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; - } - else { - return `${this.getHostUrl()}/hub/${owner}/${promptName}`; - } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; +} +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the {newDocument, result} of the operation. + * It modifies the `document` and `operation` objects - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. + * + * @param document The document to patch + * @param operation The operation to apply + * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return `{newDocument, result}` after the operation + */ +function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) { + if (typeof validateOperation == "function") { + validateOperation(operation, 0, document, operation.path); } else { - const settings = await this._getSettings(); - if (commitHash !== "latest") { - return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; - } - else { - return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; - } + validator(operation, 0); } } - async promptExists(promptIdentifier) { - const prompt = await this.getPrompt(promptIdentifier); - return !!prompt; - } - async likePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, true); - } - async unlikePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, false); - } - async *listCommits(promptOwnerAndName) { - for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { - yield* commits; + /* ROOT OPERATIONS */ + if (operation.path === "") { + let returnValue = { newDocument: document }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; } - } - async *listPrompts(options) { - const params = new URLSearchParams(); - params.append("sort_field", options?.sortField ?? "updated_at"); - params.append("sort_direction", "desc"); - params.append("is_archived", (!!options?.isArchived).toString()); - if (options?.isPublic !== undefined) { - params.append("is_public", options.isPublic.toString()); + else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document; //document we removed + return returnValue; } - if (options?.query) { - params.append("query", options.query); + else if (operation.op === "move" || operation.op === "copy") { + // it's a move or copy to root + returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field + if (operation.op === "move") { + // report removed item + returnValue.removed = document; + } + return returnValue; } - for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { - yield* prompts; + else if (operation.op === "test") { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + returnValue.newDocument = document; + return returnValue; } - } - async getPrompt(promptIdentifier) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - if (response.status === 404) { - return null; + else if (operation.op === "remove") { + // a remove on root + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; } - await raiseForStatus(response, "get prompt"); - const result = await response.json(); - if (result.repo) { - return result.repo; + else if (operation.op === "_get") { + operation.value = document; + return returnValue; } else { - return null; - } - } - async createPrompt(promptIdentifier, options) { - const settings = await this._getSettings(); - if (options?.isPublic && !settings.tenant_handle) { - throw new Error(`Cannot create a public prompt without first\n - creating a LangChain Hub handle. - You can add a handle by creating a public prompt at:\n - https://smith.langchain.com/prompts`); + /* bad operation */ + if (validateOperation) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + } + else { + return returnValue; + } } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("create a prompt", owner); + } /* END ROOT OPERATIONS */ + else { + if (!mutateDocument) { + document = helpers_deepClone(document); } - const data = { - repo_handle: promptName, - ...(options?.description && { description: options.description }), - ...(options?.readme && { readme: options.readme }), - ...(options?.tags && { tags: options.tags }), - is_public: !!options?.isPublic, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "create prompt"); - const { repo } = await response.json(); - return repo; - } - async createCommit(promptIdentifier, object, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document; + let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift + let len = keys.length; + let existingPathFragment = undefined; + let key; + let validateFunction; + if (typeof validateOperation == "function") { + validateFunction = validateOperation; } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash - ? await this._getLatestCommitHash(`${owner}/${promptName}`) - : options?.parentCommitHash; - const payload = { - manifest: JSON.parse(JSON.stringify(object)), - parent_commit: resolvedParentCommitHash, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(payload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "create commit"); - const result = await response.json(); - return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); - } - /** - * Update examples with attachments using multipart form data. - * @param updates List of ExampleUpdateWithAttachments objects to upsert - * @returns Promise with the update response - */ - async updateExamplesMultipart(datasetId, updates = []) { - return this._updateExamplesMultipart(datasetId, updates); - } - async _updateExamplesMultipart(datasetId, updates = []) { - if (!(await this._getMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + else { + validateFunction = validator; } - const formData = new FormData(); - for (const example of updates) { - const exampleId = example.id; - // Prepare the main example body - const exampleBody = { - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) { + key = unescapePathComponent(key); } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); + if (banPrototypeModifications && + (key == "__proto__" || + (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; + if (validateOperation) { + if (existingPathFragment === undefined) { + if (obj[key] === undefined) { + existingPathFragment = keys.slice(0, t).join("/"); } - else { - mimeType = attachment.mimeType; - data = attachment.data; + else if (t == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== undefined) { + validateFunction(operation, 0, document, existingPathFragment); } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); } } - if (example.attachments_operations) { - const stringifiedAttachmentsOperations = serialize(example.attachments_operations); - const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { - type: "application/json", - }); - formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + t++; + if (Array.isArray(obj)) { + if (key === "-") { + key = obj.length; + } + else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); + } // only parse key when it's an integer for `arr.prop` to work + else if (isInteger(key)) { + key = ~~key; + } + } + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + } + const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + else { + if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + obj = obj[key]; + // If we have more keys in the path, but the next value isn't a non-null object, + // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. + if (validateOperation && t < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); } } - const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetIdToUse}/examples`, { - method: "PATCH", - headers: this.headers, - body: formData, - }); - const result = await response.json(); - return result; - } - /** - * Upload examples with attachments using multipart form data. - * @param uploads List of ExampleUploadWithAttachments objects to upload - * @returns Promise with the upload response - * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead - */ - async uploadExamplesMultipart(datasetId, uploads = []) { - return this._uploadExamplesMultipart(datasetId, uploads); } - async _uploadExamplesMultipart(datasetId, uploads = []) { - if (!(await this._getMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); +} +/** + * Apply a full JSON Patch array on a JSON document. + * Returns the {newDocument, result} of the patch. + * It modifies the `document` object and `patch` - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. + * + * @param document The document to patch + * @param patch The patch to apply + * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return An array of `{newDocument, result}` after the patch + */ +function core_applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); } - const formData = new FormData(); - for (const example of uploads) { - const exampleId = (example.id ?? v4()).toString(); - // Prepare the main example body - const exampleBody = { - created_at: example.created_at, - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - ...(example.source_run_id && { source_run_id: example.source_run_id }), - ...(example.use_source_run_io && { - use_source_run_io: example.use_source_run_io, - }), - ...(example.use_source_run_attachments && { - use_source_run_attachments: example.use_source_run_attachments, - }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (!mutateDocument) { + document = helpers_deepClone(document); + } + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; // in case root was replaced + } + results.newDocument = document; + return results; +} +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the updated document. + * Suitable as a reducer. + * + * @param document The document to patch + * @param operation The operation to apply + * @return The updated document + */ +function applyReducer(document, operation, index) { + const operationResult = applyOperation(document, operation); + if (operationResult.test === false) { + // failed test + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return operationResult.newDocument; +} +/** + * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. + * @param {object} operation - operation object (patch) + * @param {number} index - index of operation in the sequence + * @param {object} [document] - object where the operation is supposed to be applied + * @param {string} [existingPathFragment] - comes along with `document` + */ +function validator(operation, index, document, existingPathFragment) { + if (typeof operation !== "object" || + operation === null || + Array.isArray(operation)) { + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); + } + else if (!objOps[operation.op]) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + } + else if (typeof operation.path !== "string") { + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); + } + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { + // paths that aren't empty string should start with "/" + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); + } + else if ((operation.op === "move" || operation.op === "copy") && + typeof operation.from !== "string") { + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + } + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + operation.value === undefined) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + } + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + hasUndefined(operation.value)) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + } + else if (document) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); + } + else if (operation.op === "replace" || + operation.op === "remove" || + operation.op === "_get") { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } + } + else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: undefined, + }; + var error = core_validate([existingValue], document); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); } } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, { - method: "POST", - headers: this.headers, - body: formData, - }); - await raiseForStatus(response, "upload examples"); - const result = await response.json(); - return result; } - async updatePrompt(promptIdentifier, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); +} +/** + * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. + * If error is encountered, returns a JsonPatchError object + * @param sequence + * @param document + * @returns {JsonPatchError|undefined} + */ +function core_validate(sequence, document, externalValidator) { + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); } - const [owner, promptName] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("update a prompt", owner); + if (document) { + //clone document and sequence so that we can safely try applying operations + core_applyPatch(helpers_deepClone(document), helpers_deepClone(sequence), externalValidator || true); } - const payload = {}; - if (options?.description !== undefined) - payload.description = options.description; - if (options?.readme !== undefined) - payload.readme = options.readme; - if (options?.tags !== undefined) - payload.tags = options.tags; - if (options?.isPublic !== undefined) - payload.is_public = options.isPublic; - if (options?.isArchived !== undefined) - payload.is_archived = options.isArchived; - // Check if payload is empty - if (Object.keys(payload).length === 0) { - throw new Error("No valid update options provided"); + else { + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) { + externalValidator(sequence[i], i, document, undefined); + } } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "PATCH", - body: JSON.stringify(payload), - headers: { - ...this.headers, - "Content-Type": "application/json", - }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update prompt"); - return response.json(); } - async deletePrompt(promptIdentifier) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); + catch (e) { + if (e instanceof JsonPatchError) { + return e; } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("delete a prompt", owner); + else { + throw e; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - return await response.json(); - } - async pullPromptCommit(promptIdentifier, options) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "pull prompt commit"); - const result = await response.json(); - return { - owner, - repo: promptName, - commit_hash: result.commit_hash, - manifest: result.manifest, - examples: result.examples, - }; - } - /** - * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. - * Using this method directly returns the JSON string of the prompt rather than a LangChain object. - * @private - */ - async _pullPrompt(promptIdentifier, options) { - const promptObject = await this.pullPromptCommit(promptIdentifier, { - includeModel: options?.includeModel, - }); - const prompt = JSON.stringify(promptObject.manifest); - return prompt; } - async pushPrompt(promptIdentifier, options) { - // Create or update prompt metadata - if (await this.promptExists(promptIdentifier)) { - if (options && Object.keys(options).some((key) => key !== "object")) { - await this.updatePrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - } - else { - await this.createPrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); +} +// based on https://github.com/epoberezkin/fast-deep-equal +// MIT License +// Copyright (c) 2017 Evgeny Poberezkin +// 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. +function _areEquals(a, b) { + if (a === b) + return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length; i-- !== 0;) + if (!_areEquals(a[i], b[i])) + return false; + return true; } - if (!options?.object) { - return await this._getPromptUrl(promptIdentifier); + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length; i-- !== 0;) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; } - // Create a commit with the new manifest - const url = await this.createCommit(promptIdentifier, options?.object, { - parentCommitHash: options?.parentCommitHash, + return true; + } + return a !== a && b !== b; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2013-2021 Joachim Wester + * MIT license + */ + + +var beforeDict = new WeakMap(); +class Mirror { + constructor(obj) { + Object.defineProperty(this, "obj", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - return url; + Object.defineProperty(this, "observers", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.obj = obj; } - /** - * Clone a public dataset to your own langsmith tenant. - * This operation is idempotent. If you already have a dataset with the given name, - * this function will do nothing. - - * @param {string} tokenOrUrl The token of the public dataset to clone. - * @param {Object} [options] Additional options for cloning the dataset. - * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. - * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. - * @returns {Promise} - */ - async clonePublicDataset(tokenOrUrl, options = {}) { - const { sourceApiUrl = this.apiUrl, datasetName } = options; - const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); - const sourceClient = new Client({ - apiUrl: parsedApiUrl, - // Placeholder API key not needed anymore in most cases, but - // some private deployments may have API key-based rate limiting - // that would cause this to fail if we provide no value. - apiKey: "placeholder", +} +class ObserverInfo { + constructor(callback, observer) { + Object.defineProperty(this, "callback", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - const ds = await sourceClient.readSharedDataset(tokenUuid); - const finalDatasetName = datasetName || ds.name; - try { - if (await this.hasDataset({ datasetId: finalDatasetName })) { - console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); - return; - } - } - catch (_) { - // `.hasDataset` will throw an error if the dataset does not exist. - // no-op in that case - } - // Fetch examples first, then create the dataset - const examples = await sourceClient.listSharedExamples(tokenUuid); - const dataset = await this.createDataset(finalDatasetName, { - description: ds.description, - dataType: ds.data_type || "kv", - inputsSchema: ds.inputs_schema_definition ?? undefined, - outputsSchema: ds.outputs_schema_definition ?? undefined, + Object.defineProperty(this, "observer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - try { - await this.createExamples({ - inputs: examples.map((e) => e.inputs), - outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), - datasetId: dataset.id, - }); - } - catch (e) { - console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + - "You should delete it manually."); - throw e; + this.callback = callback; + this.observer = observer; + } +} +function getMirror(obj) { + return beforeDict.get(obj); +} +function getObserverFromMirror(mirror, callback) { + return mirror.observers.get(callback); +} +function removeObserverFromMirror(mirror, observer) { + mirror.observers.delete(observer.callback); +} +/** + * Detach an observer from an object + */ +function unobserve(root, observer) { + observer.unobserve(); +} +/** + * Observes changes made to an object, which can then be retrieved using generate + */ +function observe(obj, callback) { + var patches = []; + var observer; + var mirror = getMirror(obj); + if (!mirror) { + mirror = new Mirror(obj); + beforeDict.set(obj, mirror); + } + else { + const observerInfo = getObserverFromMirror(mirror, callback); + observer = observerInfo && observerInfo.observer; + } + if (observer) { + return observer; + } + observer = {}; + mirror.value = _deepClone(obj); + if (callback) { + observer.callback = callback; + observer.next = null; + var dirtyCheck = () => { + duplex_generate(observer); + }; + var fastCheck = () => { + clearTimeout(observer.next); + observer.next = setTimeout(dirtyCheck); + }; + if (typeof window !== "undefined") { + //not Node + window.addEventListener("mouseup", fastCheck); + window.addEventListener("keyup", fastCheck); + window.addEventListener("mousedown", fastCheck); + window.addEventListener("keydown", fastCheck); + window.addEventListener("change", fastCheck); } } - parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { - // Try parsing as UUID - try { - assertUuid(urlOrToken); // Will throw if it's not a UUID. - return [apiUrl, urlOrToken]; + observer.patches = patches; + observer.object = obj; + observer.unobserve = () => { + duplex_generate(observer); + clearTimeout(observer.next); + removeObserverFromMirror(mirror, observer); + if (typeof window !== "undefined") { + window.removeEventListener("mouseup", fastCheck); + window.removeEventListener("keyup", fastCheck); + window.removeEventListener("mousedown", fastCheck); + window.removeEventListener("keydown", fastCheck); + window.removeEventListener("change", fastCheck); } - catch (_) { - // no-op if it's not a uuid + }; + mirror.observers.set(callback, new ObserverInfo(callback, observer)); + return observer; +} +/** + * Generate an array of patches from an observer + */ +function duplex_generate(observer, invertible = false) { + var mirror = beforeDict.get(observer.object); + _generate(mirror.value, observer.object, observer.patches, "", invertible); + if (observer.patches.length) { + applyPatch(mirror.value, observer.patches); + } + var temp = observer.patches; + if (temp.length > 0) { + observer.patches = []; + if (observer.callback) { + observer.callback(temp); } - // Parse as URL - try { - const parsedUrl = new URL(urlOrToken); - const pathParts = parsedUrl.pathname - .split("/") - .filter((part) => part !== ""); - if (pathParts.length >= numParts) { - const tokenUuid = pathParts[pathParts.length - numParts]; - return [apiUrl, tokenUuid]; + } + return temp; +} +// Dirty check if obj is different from mirror, generate patches and update mirror +function _generate(mirror, obj, patches, path, invertible) { + if (obj === mirror) { + return; + } + if (typeof obj.toJSON === "function") { + obj = obj.toJSON(); + } + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var changed = false; + var deleted = false; + //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (helpers_hasOwnProperty(obj, key) && + !(obj[key] === undefined && + oldVal !== undefined && + Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && + oldVal != null && + typeof newVal == "object" && + newVal != null && + Array.isArray(oldVal) === Array.isArray(newVal)) { + _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); } else { - throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + if (oldVal !== newVal) { + changed = true; + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(oldVal), + }); + } + patches.push({ + op: "replace", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(newVal), + }); + } } } - catch (error) { - throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); - } - } - /** - * Awaits all pending trace batches. Useful for environments where - * you need to be sure that all tracing requests finish before execution ends, - * such as serverless environments. - * - * @example - * ``` - * import { Client } from "langsmith"; - * - * const client = new Client(); - * - * try { - * // Tracing happens here - * ... - * } finally { - * await client.awaitPendingTraceBatches(); - * } - * ``` - * - * @returns A promise that resolves once all currently pending traces have sent. - */ - awaitPendingTraceBatches() { - if (this.manualFlushMode) { - console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); - return Promise.resolve(); + else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(oldVal), + }); + } + patches.push({ + op: "remove", + path: path + "/" + escapePathComponent(key), + }); + deleted = true; // property has been deleted + } + else { + if (invertible) { + patches.push({ op: "test", path, value: mirror }); + } + patches.push({ op: "replace", path, value: obj }); + changed = true; + } + } + if (!deleted && newKeys.length == oldKeys.length) { + return; + } + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== undefined) { + patches.push({ + op: "add", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(obj[key]), + }); } - return Promise.all([ - ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), - this.batchIngestCaller.queue.onIdle(), - ]); } } -function isExampleCreate(input) { - return "dataset_id" in input || "dataset_name" in input; +/** + * Create an array of patches from the differences in two objects + */ +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; } -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js -// Update using yarn bump-version -const __version__ = "0.3.28"; +/** + * Default export for backwards compat + */ -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js -// Inlined from https://github.com/flexdinesh/browser-or-node -let globalEnv; -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && +/* harmony default export */ const fast_json_patch = ({ + ...src_core_namespaceObject, + // ...duplex, + JsonPatchError: PatchError, + deepClone: helpers_deepClone, + escapePathComponent: escapePathComponent, + unescapePathComponent: unescapePathComponent, +}); + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js +const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const env_isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && - (navigator.userAgent.includes("Node.js") || - navigator.userAgent.includes("jsdom"))); +const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); // Supabase Edge Function provides a `Deno` global object // without `version` property -const isDeno = () => typeof Deno !== "undefined"; +const env_isDeno = () => typeof Deno !== "undefined"; // Mark not-as-node if in Supabase Edge Function -const isNode = () => typeof process !== "undefined" && +const env_isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && - !isDeno(); -const getEnv = () => { - if (globalEnv) { - return globalEnv; - } - if (isBrowser()) { - globalEnv = "browser"; + !env_isDeno(); +const env_getEnv = () => { + let env; + if (env_isBrowser()) { + env = "browser"; } - else if (isNode()) { - globalEnv = "node"; + else if (env_isNode()) { + env = "node"; } - else if (isWebWorker()) { - globalEnv = "webworker"; + else if (env_isWebWorker()) { + env = "webworker"; } - else if (isJsDom()) { - globalEnv = "jsdom"; + else if (env_isJsDom()) { + env = "jsdom"; } - else if (isDeno()) { - globalEnv = "deno"; + else if (env_isDeno()) { + env = "deno"; } else { - globalEnv = "other"; + env = "other"; } - return globalEnv; + return env; }; -let runtimeEnvironment; -function getRuntimeEnvironment() { - if (runtimeEnvironment === undefined) { - const env = getEnv(); - const releaseEnv = getShas(); - runtimeEnvironment = { - library: "langsmith", +let env_runtimeEnvironment; +async function env_getRuntimeEnvironment() { + if (env_runtimeEnvironment === undefined) { + const env = env_getEnv(); + env_runtimeEnvironment = { + library: "langchain-js", runtime: env, - sdk: "langsmith-js", - sdk_version: __version__, - ...releaseEnv, }; } - return runtimeEnvironment; -} -/** - * Retrieves the LangChain-specific environment variables from the current runtime environment. - * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security. - * - * @returns {Record} - * - A record of LangChain-specific environment variables. - */ -function getLangChainEnvVars() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - for (const [key, value] of Object.entries(allEnvVars)) { - if (key.startsWith("LANGCHAIN_") && typeof value === "string") { - envVars[key] = value; - } - } - for (const key in envVars) { - if ((key.toLowerCase().includes("key") || - key.toLowerCase().includes("secret") || - key.toLowerCase().includes("token")) && - typeof envVars[key] === "string") { - const value = envVars[key]; - envVars[key] = - value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); - } - } - return envVars; -} -/** - * Retrieves the LangChain-specific metadata from the current runtime environment. - * - * @returns {Record} - * - A record of LangChain-specific metadata environment variables. - */ -function getLangChainEnvVarsMetadata() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - const excluded = [ - "LANGCHAIN_API_KEY", - "LANGCHAIN_ENDPOINT", - "LANGCHAIN_TRACING_V2", - "LANGCHAIN_PROJECT", - "LANGCHAIN_SESSION", - "LANGSMITH_API_KEY", - "LANGSMITH_ENDPOINT", - "LANGSMITH_TRACING_V2", - "LANGSMITH_PROJECT", - "LANGSMITH_SESSION", - ]; - for (const [key, value] of Object.entries(allEnvVars)) { - if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && - typeof value === "string" && - !excluded.includes(key) && - !key.toLowerCase().includes("key") && - !key.toLowerCase().includes("secret") && - !key.toLowerCase().includes("token")) { - if (key === "LANGCHAIN_REVISION_ID") { - envVars["revision_id"] = value; - } - else { - envVars[key] = value; - } - } - } - return envVars; + return env_runtimeEnvironment; } -/** - * Retrieves the environment variables from the current runtime environment. - * - * This function is designed to operate in a variety of JS environments, - * including Node.js, Deno, browsers, etc. - * - * @returns {Record | undefined} - * - A record of environment variables if available. - * - `undefined` if the environment does not support or allows access to environment variables. - */ -function getEnvironmentVariables() { +function env_getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/langchain-ai/langchainjs/issues/1412 try { - // Check for Node.js environment - // eslint-disable-next-line no-process-env - if (typeof process !== "undefined" && process.env) { + if (typeof process !== "undefined") { // eslint-disable-next-line no-process-env - return Object.entries(process.env).reduce((acc, [key, value]) => { - acc[key] = String(value); - return acc; - }, {}); + return process.env?.[name]; + } + else if (env_isDeno()) { + return Deno?.env.get(name); + } + else { + return undefined; } - // For browsers and other environments, we may not have direct access to env variables - // Return undefined or any other fallback as required. - return undefined; - } - catch (e) { - // Catch any errors that might occur while trying to access environment variables - return undefined; - } -} -function getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; } catch (e) { return undefined; } } -function getLangSmithEnvironmentVariable(name) { - return (getEnvironmentVariable(`LANGSMITH_${name}`) || - getEnvironmentVariable(`LANGCHAIN_${name}`)); -} -function setEnvironmentVariable(name, value) { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - process.env[name] = value; - } -} -let cachedCommitSHAs; -/** - * Get the Git commit SHA from common environment variables - * used by different CI/CD platforms. - * @returns {string | undefined} The Git commit SHA or undefined if not found. - */ -function getShas() { - if (cachedCommitSHAs !== undefined) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT", - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = getEnvironmentVariable(env); - if (envVar !== undefined) { - shas[env] = envVar; - } - } - cachedCommitSHAs = shas; - return shas; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js - -const isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; - } - const envVars = ["TRACING_V2", "TRACING"]; - return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js -const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js - - +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js -function stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); +/** + * Abstract class that provides a set of optional methods that can be + * overridden in derived classes to handle various events during the + * execution of a LangChain application. + */ +class BaseCallbackHandlerMethodsClass { } -function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { - // Date only has millisecond precision, so we use the microseconds to break - // possible ties, avoiding incorrect run order - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); +function callbackHandlerPrefersStreaming(x) { + return "lc_prefer_streaming" in x && x.lc_prefer_streaming; } /** - * Baggage header information + * Abstract base class for creating callback handlers in the LangChain + * framework. It provides a set of optional methods that can be overridden + * in derived classes to handle various events during the execution of a + * LangChain application. */ -class Baggage { - constructor(metadata, tags, project_name) { - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.metadata = metadata; - this.tags = tags; - this.project_name = project_name; +class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { + get lc_namespace() { + return ["langchain_core", "callbacks", this.name]; } - static fromHeader(value) { - const items = value.split(","); - let metadata = {}; - let tags = []; - let project_name; - for (const item of items) { - const [key, uriValue] = item.split("="); - const value = decodeURIComponent(uriValue); - if (key === "langsmith-metadata") { - metadata = JSON.parse(value); - } - else if (key === "langsmith-tags") { - tags = value.split(","); - } - else if (key === "langsmith-project") { - project_name = value; - } - } - return new Baggage(metadata, tags, project_name); + get lc_secrets() { + return undefined; } - toHeader() { - const items = []; - if (this.metadata && Object.keys(this.metadata).length > 0) { - items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); - } - if (this.tags && this.tags.length > 0) { - items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); - } - if (this.project_name) { - items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); - } - return items.join(","); + get lc_attributes() { + return undefined; } -} -class run_trees_RunTree { - constructor(originalConfig) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "end_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "extra", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "serialized", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputs", { + get lc_aliases() { + return undefined; + } + get lc_serializable_keys() { + return undefined; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor), + ]; + } + constructor(input) { + super(); + Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "reference_example_id", { + Object.defineProperty(this, "lc_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "client", { + Object.defineProperty(this, "ignoreLLM", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "events", { + Object.defineProperty(this, "ignoreChain", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "trace_id", { + Object.defineProperty(this, "ignoreAgent", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "dotted_order", { + Object.defineProperty(this, "ignoreRetriever", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "tracingEnabled", { + Object.defineProperty(this, "ignoreCustomEvent", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "execution_order", { + Object.defineProperty(this, "raiseError", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - Object.defineProperty(this, "child_execution_order", { + Object.defineProperty(this, "awaitHandlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" }); - /** - * Attachments associated with the run. - * Each entry is a tuple of [mime_type, bytes] - */ - Object.defineProperty(this, "attachments", { + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + this.ignoreCustomEvent = + input.ignoreCustomEvent ?? this.ignoreCustomEvent; + this.raiseError = input.raiseError ?? this.raiseError; + this.awaitHandlers = + this.raiseError || (input._awaitHandler ?? this.awaitHandlers); + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return Serializable.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return Serializable.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4() + }); + Object.assign(this, methods); + } + } + return new Handler(); + } +} +const isBaseCallbackHandler = (x) => { + const callbackHandler = x; + return (callbackHandler !== undefined && + typeof callbackHandler.copy === "function" && + typeof callbackHandler.name === "string" && + typeof callbackHandler.awaitHandlers === "boolean"); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" + ? value + : { [defaultKey]: value }; +} +function base_stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function base_convertToDottedOrderFormat(epoch, runId, executionOrder) { + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + return (base_stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); +} +function isBaseTracer(x) { + return typeof x._addRunToRunMap === "function"; +} +class BaseTracer extends BaseCallbackHandler { + constructor(_fields) { + super(...arguments); + Object.defineProperty(this, "runMap", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: new Map() }); - // If you pass in a run tree directly, return a shallow clone - if (run_trees_isRunTree(originalConfig)) { - Object.assign(this, { ...originalConfig }); - return; + } + copy() { + return this; + } + stringifyError(error) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + return error.message + (error?.stack ? `\n\n${error.stack}` : ""); } - const defaultConfig = run_trees_RunTree.getDefaultConfig(); - const { metadata, ...config } = originalConfig; - const client = config.client ?? run_trees_RunTree.getSharedClient(); - const dedupedMetadata = { - ...metadata, - ...config?.extra?.metadata, - }; - config.extra = { ...config.extra, metadata: dedupedMetadata }; - Object.assign(this, { ...defaultConfig, ...config, client }); - if (!this.trace_id) { - if (this.parent_run) { - this.trace_id = this.parent_run.trace_id ?? this.id; - } - else { - this.trace_id = this.id; - } + if (typeof error === "string") { + return error; } - this.execution_order ??= 1; - this.child_execution_order ??= 1; - if (!this.dotted_order) { - const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); - if (this.parent_run) { - this.dotted_order = - this.parent_run.dotted_order + "." + currentDottedOrder; + return `${error}`; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + _addRunToRunMap(run) { + const currentDottedOrder = base_convertToDottedOrderFormat(run.start_time, run.id, run.execution_order); + const storedRun = { ...run }; + if (storedRun.parent_run_id !== undefined) { + const parentRun = this.runMap.get(storedRun.parent_run_id); + if (parentRun) { + this._addChildRun(parentRun, storedRun); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); + storedRun.trace_id = parentRun.trace_id; + if (parentRun.dotted_order !== undefined) { + storedRun.dotted_order = [ + parentRun.dotted_order, + currentDottedOrder, + ].join("."); + } + else { + // This can happen naturally for callbacks added within a run + // console.debug(`Parent run with UUID ${storedRun.parent_run_id} has no dotted order.`); + } } else { - this.dotted_order = currentDottedOrder; + // This can happen naturally for callbacks added within a run + // console.debug( + // `Parent run with UUID ${storedRun.parent_run_id} not found.` + // ); } } + else { + storedRun.trace_id = storedRun.id; + storedRun.dotted_order = currentDottedOrder; + } + this.runMap.set(storedRun.id, storedRun); + return storedRun; + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); + if (parentRun) { + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } + else { + await this.persistRun(run); + } + this.runMap.delete(run.id); + await this.onRunUpdate?.(run); } - static getDefaultConfig() { - return { - id: v4(), - run_type: "chain", - project_name: getLangSmithEnvironmentVariable("PROJECT") ?? - getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default", + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); + // If a run has no parent then execution order is 1 + if (!parentRun) { + return 1; + } + return parentRun.child_execution_order + 1; + } + /** + * Create and add a run to the run map for LLM start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { prompts }, + execution_order, child_runs: [], - api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time: Date.now(), - serialized: {}, - inputs: {}, - extra: {}, + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], }; + return this._addRunToRunMap(run); } - static getSharedClient() { - if (!run_trees_RunTree.sharedClient) { - run_trees_RunTree.sharedClient = new Client(); - } - return run_trees_RunTree.sharedClient; + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.runMap.get(runId) ?? + this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; } - createChild(config) { - const child_execution_order = this.child_execution_order + 1; - const child = new run_trees_RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - client: this.client, - tracingEnabled: this.tracingEnabled, - execution_order: child_execution_order, - child_execution_order: child_execution_order, - }); - // Copy context vars over into the new run tree. - if (_LC_CONTEXT_VARIABLES_KEY in this) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - child[_LC_CONTEXT_VARIABLES_KEY] = - this[_LC_CONTEXT_VARIABLES_KEY]; - } - const LC_CHILD = Symbol.for("lc:child_config"); - const presentConfig = config.extra?.[LC_CHILD] ?? - this.extra[LC_CHILD]; - // tracing for LangChain is defined by the _parentRunId and runMap of the tracer - if (isRunnableConfigLike(presentConfig)) { - const newConfig = { ...presentConfig }; - const callbacks = isCallbackManagerLike(newConfig.callbacks) - ? newConfig.callbacks.copy?.() - : undefined; - if (callbacks) { - // update the parent run id - Object.assign(callbacks, { _parentRunId: child.id }); - // only populate if we're in a newer LC.JS version - callbacks.handlers - ?.find(isLangChainTracerLike) - ?.updateFromRunTree?.(child); - newConfig.callbacks = callbacks; - } - child.extra[LC_CHILD] = newConfig; - } - // propagate child_execution_order upwards - const visited = new Set(); - let current = this; - while (current != null && !visited.has(current.id)) { - visited.add(current.id); - current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); - current = current.parent_run; + /** + * Create and add a run to the run map for chat model start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata + ? { ...extraParams, metadata } + : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.runMap.get(runId) ?? + this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); } - this.child_runs.push(child); - return child; + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; } - async end(outputs, error, endTime = Date.now(), metadata) { - this.outputs = this.outputs ?? outputs; - this.error = this.error ?? error; - this.end_time = this.end_time ?? endTime; - if (metadata && Object.keys(metadata).length > 0) { - this.extra = this.extra - ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } - : { metadata }; + async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMError?.(run); + await this._endTrace(run); + return run; } - _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - if (!runExtra.runtime) { - runExtra.runtime = {}; + /** + * Create and add a run to the run map for chain start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const run = this.runMap.get(runId) ?? + this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); + await this.onRunCreate?.(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.runMap.get(runId); + if (!run) { + throw new Error("No chain run to end."); } - if (runtimeEnv) { - for (const [k, v] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k]) { - runExtra.runtime[k] = v; - } - } + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); - parent_run_id = undefined; + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.runMap.get(runId); + if (!run) { + throw new Error("No chain run to end."); } - else { - parent_run_id = run.parent_run?.id; - child_runs = []; + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + if (kwargs?.inputs !== undefined) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); } - const persistedRun = { - id: run.id, - name: run.name, - start_time: run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs: child_runs, - parent_run_id: parent_run_id, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - tags: run.tags, - attachments: run.attachments, + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for tool start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool.id[tool.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], }; - return persistedRun; + return this._addRunToRunMap(run); } - async postRun(excludeChildRuns = true) { - try { - const runtimeEnv = getRuntimeEnvironment(); - const runCreate = await this._convertToCreate(this, runtimeEnv, true); - await this.client.createRun(runCreate); - if (!excludeChildRuns) { - warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); - } - } - } - catch (error) { - console.error(`Error in postRun for run ${this.id}:`, error); + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const run = this.runMap.get(runId) ?? + this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onToolStart?.(run); + return run; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); } + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), + }); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; } - async patchRun() { - try { - const runUpdate = { - end_time: this.end_time, - error: this.error, - inputs: this.inputs, - outputs: this.outputs, - parent_run_id: this.parent_run?.id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, - dotted_order: this.dotted_order, - trace_id: this.trace_id, - tags: this.tags, - attachments: this.attachments, - session_name: this.project_name, - }; - await this.client.updateRun(this.id, runUpdate); + async handleToolError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); } - catch (error) { - console.error(`Error in patchRun for run ${this.id}`, error); + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), + }); + await this.onToolError?.(run); + await this._endTrace(run); + return run; + } + async handleAgentAction(action, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; } + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: new Date().toISOString(), + kwargs: { action }, + }); + await this.onAgentAction?.(run); } - toJSON() { - return this._convertToCreate(this, undefined, false); + async handleAgentEnd(action, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "agent_end", + time: new Date().toISOString(), + kwargs: { action }, + }); + await this.onAgentEnd?.(run); } /** - * Add an event to the run tree. - * @param event - A single event or string to add + * Create and add a run to the run map for retriever start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. */ - addEvent(event) { - if (!this.events) { - this.events = []; - } - if (typeof event === "string") { - this.events.push({ - name: "event", - time: new Date().toISOString(), - message: event, - }); - } - else { - this.events.push({ - ...event, - time: event.time ?? new Date().toISOString(), - }); - } + _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [ + { + name: "start", + time: new Date(start_time).toISOString(), + }, + ], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [], + }; + return this._addRunToRunMap(run); } - static fromRunnableConfig(parentConfig, props) { - // We only handle the callback manager case for now - const callbackManager = parentConfig?.callbacks; - let parentRun; - let projectName; - let client; - let tracingEnabled = isTracingEnabled(); - if (callbackManager) { - const parentRunId = callbackManager?.getParentRunId?.() ?? ""; - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); - parentRun = langChainTracer?.getRun?.(parentRunId); - projectName = langChainTracer?.projectName; - client = langChainTracer?.client; - tracingEnabled = tracingEnabled || !!langChainTracer; - } - if (!parentRun) { - return new run_trees_RunTree({ - ...props, - client, - tracingEnabled, - project_name: projectName, - }); + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const run = this.runMap.get(runId) ?? + this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); } - const parentRunTree = new run_trees_RunTree({ - name: parentRun.name, - id: parentRun.id, - trace_id: parentRun.trace_id, - dotted_order: parentRun.dotted_order, - client, - tracingEnabled, - project_name: projectName, - tags: [ - ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), - ], - extra: { - metadata: { - ...parentRun?.extra?.metadata, - ...parentConfig?.metadata, - }, - }, + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString(), }); - return parentRunTree.createChild(props); - } - static fromDottedOrder(dottedOrder) { - return this.fromHeaders({ "langsmith-trace": dottedOrder }); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; } - static fromHeaders(headers, inheritArgs) { - const rawHeaders = "get" in headers && typeof headers.get === "function" - ? { - "langsmith-trace": headers.get("langsmith-trace"), - baggage: headers.get("baggage"), - } - : headers; - const headerTrace = rawHeaders["langsmith-trace"]; - if (!headerTrace || typeof headerTrace !== "string") - return undefined; - const parentDottedOrder = headerTrace.trim(); - const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { - const [strTime, uuid] = part.split("Z"); - return { strTime, time: Date.parse(strTime + "Z"), uuid }; + async handleRetrieverError(error, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString(), }); - const traceId = parsedDottedOrder[0].uuid; - const config = { - ...inheritArgs, - name: inheritArgs?.["name"] ?? "parent", - run_type: inheritArgs?.["run_type"] ?? "chain", - start_time: inheritArgs?.["start_time"] ?? Date.now(), - id: parsedDottedOrder.at(-1)?.uuid, - trace_id: traceId, - dotted_order: parentDottedOrder, - }; - if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { - const baggage = Baggage.fromHeader(rawHeaders["baggage"]); - config.metadata = baggage.metadata; - config.tags = baggage.tags; - config.project_name = baggage.project_name; + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; + } + async handleText(text, runId) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "chain") { + return; } - return new run_trees_RunTree(config); + run.events.push({ + name: "text", + time: new Date().toISOString(), + kwargs: { text }, + }); + await this.onText?.(run); } - toHeaders(headers) { - const result = { - "langsmith-trace": this.dotted_order, - baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name).toHeader(), - }; - if (headers) { - for (const [key, value] of Object.entries(result)) { - headers.set(key, value); - } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.runMap.get(runId); + if (!run || run?.run_type !== "llm") { + throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); } - return result; + run.events.push({ + name: "new_token", + time: new Date().toISOString(), + kwargs: { token, idx, chunk: fields?.chunk }, + }); + await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); + return run; } } -Object.defineProperty(run_trees_RunTree, "sharedClient", { - enumerable: true, - configurable: true, - writable: true, - value: null -}); -function run_trees_isRunTree(x) { - return (x !== undefined && - typeof x.createChild === "function" && - typeof x.postRun === "function"); -} -function isLangChainTracerLike(x) { - return (typeof x === "object" && - x != null && - typeof x.name === "string" && - x.name === "langchain_tracer"); -} -function containsLangChainTracerLike(x) { - return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); -} -function isCallbackManagerLike(x) { - return (typeof x === "object" && - x != null && - Array.isArray(x.handlers)); -} -function isRunnableConfigLike(x) { - // Check that it's an object with a callbacks arg - // that has either a CallbackManagerLike object with a langchain tracer within it - // or an array with a LangChainTracerLike object within it - return (x !== undefined && - typeof x.callbacks === "object" && - // Callback manager with a langchain tracer - (containsLangChainTracerLike(x.callbacks?.handlers) || - // Or it's an array with a LangChainTracerLike object within it - containsLangChainTracerLike(x.callbacks))); -} -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js +// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/ansi-styles/index.js +var ansi_styles = __nccwpck_require__(2227); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js -class MockAsyncLocalStorage { - getStore() { - return undefined; + +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); } - run(_, callback) { - return callback(); + catch (err) { + return fallback; } } -const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const mockAsyncLocalStorage = new MockAsyncLocalStorage(); -class AsyncLocalStorageProvider { - getInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; +function formatKVMapItem(value) { + if (typeof value === "string") { + return value.trim(); } - initializeGlobalInstance(instance) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[TRACING_ALS_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[TRACING_ALS_KEY] = instance; - } + if (value === null || value === undefined) { + return value; } + return tryJsonStringify(value, value.toString()); } -const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); +function elapsed(run) { + if (!run.end_time) + return ""; + const elapsed = run.end_time - run.start_time; + if (elapsed < 1000) { + return `${elapsed}ms`; + } + return `${(elapsed / 1000).toFixed(2)}s`; +} +const { color } = ansi_styles; /** - * Return the current run tree from within a traceable-wrapped function. - * Will throw an error if called outside of a traceable function. + * A tracer that logs all events to the console. It extends from the + * `BaseTracer` class and overrides its methods to provide custom logging + * functionality. + * @example + * ```typescript + * + * const llm = new ChatAnthropic({ + * temperature: 0, + * tags: ["example", "callbacks", "constructor"], + * callbacks: [new ConsoleCallbackHandler()], + * }); * - * @returns The run tree for the given context. + * ``` */ -const getCurrentRunTree = () => { - const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); - if (!run_trees_isRunTree(runTree)) { - throw new Error([ - "Could not get the current run tree.", - "", - "Please make sure you are calling this method within a traceable function and that tracing is enabled.", - ].join("\n")); +class ConsoleCallbackHandler extends BaseTracer { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "console_callback_handler" + }); } - return runTree; -}; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function withRunTree(runTree, fn) { - const storage = AsyncLocalStorageProviderSingleton.getInstance(); - return new Promise((resolve, reject) => { - storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); - }); -} -const ROOT = Symbol.for("langsmith:traceable:root"); -function isTraceableFunction(x -// eslint-disable-next-line @typescript-eslint/no-explicit-any -) { - return typeof x === "function" && "langsmith:traceable" in x; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */ -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function helpers_hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys = new Array(obj.length); - for (let k = 0; k < keys.length; k++) { - keys[k] = "" + k; + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + // utility methods + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; + } + else { + break; + } } - return keys; + return parents; } - if (Object.keys) { - return Object.keys(obj); + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string = [...parents, run] + .map((parent, i, arr) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; + }) + .join(" > "); + return wrap(color.grey, string); } - let keys = []; - for (let i in obj) { - if (helpers_hasOwnProperty(obj, i)) { - keys.push(i); - } + // logging methods + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); } - return keys; -} -/** - * Deeply clone the object. - * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) - * @param {any} obj value to clone - * @return {any} cloned obj - */ -function helpers_deepClone(obj) { - switch (typeof obj) { - case "object": - return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 - case "undefined": - return null; //this is how JSON.stringify behaves for array items - default: - return obj; //no need to clone primitives + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs + ? { prompts: run.inputs.prompts.map((p) => p.trim()) } + : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); } -} -//3x faster than cached /^\d+$/.test(str) -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; - } - return false; + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } - return true; -} -/** - * Escapes a json pointer path - * @param path The raw pointer - * @return the Escaped path - */ -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** - * Unescapes a json pointer path - * @param path The escaped pointer - * @return The unescaped path - */ -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -function _getPathRecursive(root, obj) { - let found; - for (let key in root) { - if (helpers_hasOwnProperty(root, key)) { - if (root[key] === obj) { - return escapePathComponent(key) + "/"; - } - else if (typeof root[key] === "object") { - found = _getPathRecursive(root[key], obj); - if (found != "") { - return escapePathComponent(key) + "/" + found; - } - } - } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); } - return ""; -} -function getPath(root, obj) { - if (root === obj) { - return "/"; + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); } - const path = _getPathRecursive(root, obj); - if (path === "") { - throw new Error("Object not found in root"); + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } - return `/${path}`; -} -/** - * Recursively checks whether an object has any undefined values inside. - */ -function hasUndefined(obj) { - if (obj === undefined) { - return true; + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); } - if (obj) { - if (Array.isArray(obj)) { - for (let i = 0, len = obj.length; i < len; i++) { - if (hasUndefined(obj[i])) { - return true; - } - } - } - else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) { - if (hasUndefined(obj[objKeys[i]])) { - return true; - } - } - } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" - ? JSON.stringify(args[key], null, 2) - : args[key]; // pretty print - if (typeof value !== "undefined") { - messageParts.push(`${key}: ${value}`); - } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); } - return messageParts.join("\n"); } -class PatchError extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { name, index, operation, tree })); + +;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js + +;// CONCATENATED MODULE: ./node_modules/langsmith/index.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js + + +let client; +const getDefaultLangChainClientSingleton = () => { + if (client === undefined) { + const clientParams = env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + ? { + // LangSmith has its own backgrounding system + blockOnRootRunFinalization: true, + } + : {}; + client = new Client(clientParams); + } + return client; +}; +const setDefaultLangChainClientSingleton = (newClient) => { + client = newClient; +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js + + + + + +class tracer_langchain_LangChainTracer extends BaseTracer { + constructor(fields = {}) { + super(fields); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: name + value: "langchain_tracer" }); - Object.defineProperty(this, "index", { + Object.defineProperty(this, "projectName", { enumerable: true, configurable: true, writable: true, - value: index + value: void 0 }); - Object.defineProperty(this, "operation", { + Object.defineProperty(this, "exampleId", { enumerable: true, configurable: true, writable: true, - value: operation + value: void 0 }); - Object.defineProperty(this, "tree", { + Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, - value: tree - }); - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree, - }); - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js -// @ts-nocheck - -const JsonPatchError = PatchError; -const deepClone = helpers_deepClone; -/* We use a Javascript hash to store each - function. Each hash entry (property) uses - the operation identifiers specified in rfc6902. - In this way, we can map each patch operation - to its dedicated function in efficient way. - */ -/* The operations applicable to an object */ -const objOps = { - add: function (obj, key, document) { - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function (obj, key, document) { - var removed = obj[key]; - delete obj[key]; - return { newDocument: document, removed }; - }, - replace: function (obj, key, document) { - var removed = obj[key]; - obj[key] = this.value; - return { newDocument: document, removed }; - }, - move: function (obj, key, document) { - /* in case move target overwrites an existing value, - return the removed value, this can be taxing performance-wise, - and is potentially unneeded */ - let removed = getValueByPointer(document, this.path); - if (removed) { - removed = helpers_deepClone(removed); - } - const originalValue = applyOperation(document, { - op: "remove", - path: this.from, - }).removed; - applyOperation(document, { - op: "add", - path: this.path, - value: originalValue, - }); - return { newDocument: document, removed }; - }, - copy: function (obj, key, document) { - const valueToCopy = getValueByPointer(document, this.from); - // enforce copy by value so further operations don't affect source (see issue #177) - applyOperation(document, { - op: "add", - path: this.path, - value: helpers_deepClone(valueToCopy), + value: void 0 }); - return { newDocument: document }; - }, - test: function (obj, key, document) { - return { newDocument: document, test: _areEquals(obj[key], this.value) }; - }, - _get: function (obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - }, -}; -/* The operations applicable to an array. Many are the same as for the object */ -var arrOps = { - add: function (arr, i, document) { - if (isInteger(i)) { - arr.splice(i, 0, this.value); - } - else { - // array props - arr[i] = this.value; + const { exampleId, projectName, client } = fields; + this.projectName = + projectName ?? + env_getEnvironmentVariable("LANGCHAIN_PROJECT") ?? + env_getEnvironmentVariable("LANGCHAIN_SESSION"); + this.exampleId = exampleId; + this.client = client ?? getDefaultLangChainClientSingleton(); + const traceableTree = tracer_langchain_LangChainTracer.getTraceableRunTree(); + if (traceableTree) { + this.updateFromRunTree(traceableTree); } - // this may be needed when using '-' in an array - return { newDocument: document, index: i }; - }, - remove: function (arr, i, document) { - var removedList = arr.splice(i, 1); - return { newDocument: document, removed: removedList[0] }; - }, - replace: function (arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { newDocument: document, removed }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get, -}; -/** - * Retrieves a value from a JSON document by a JSON pointer. - * Returns the value. - * - * @param document The document to get the value from - * @param pointer an escaped JSON pointer - * @return The retrieved value - */ -function getValueByPointer(document, pointer) { - if (pointer == "") { - return document; } - var getOriginalDestination = { op: "_get", path: pointer }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; -} -/** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the {newDocument, result} of the operation. - * It modifies the `document` and `operation` objects - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. - * - * @param document The document to patch - * @param operation The operation to apply - * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return `{newDocument, result}` after the operation - */ -function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) { - if (typeof validateOperation == "function") { - validateOperation(operation, 0, document, operation.path); - } - else { - validator(operation, 0); - } + async _convertToCreate(run, example_id = undefined) { + return { + ...run, + extra: { + ...run.extra, + runtime: await env_getRuntimeEnvironment(), + }, + child_runs: undefined, + session_name: this.projectName, + reference_example_id: run.parent_run_id ? undefined : example_id, + }; } - /* ROOT OPERATIONS */ - if (operation.path === "") { - let returnValue = { newDocument: document }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } - else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document; //document we removed - return returnValue; - } - else if (operation.op === "move" || operation.op === "copy") { - // it's a move or copy to root - returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field - if (operation.op === "move") { - // report removed item - returnValue.removed = document; - } - return returnValue; - } - else if (operation.op === "test") { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - returnValue.newDocument = document; - return returnValue; - } - else if (operation.op === "remove") { - // a remove on root - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; - } - else if (operation.op === "_get") { - operation.value = document; - return returnValue; - } - else { - /* bad operation */ - if (validateOperation) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else { - return returnValue; - } - } - } /* END ROOT OPERATIONS */ - else { - if (!mutateDocument) { - document = helpers_deepClone(document); - } - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document; - let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift - let len = keys.length; - let existingPathFragment = undefined; - let key; - let validateFunction; - if (typeof validateOperation == "function") { - validateFunction = validateOperation; - } - else { - validateFunction = validator; - } - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) { - key = unescapePathComponent(key); - } - if (banPrototypeModifications && - (key == "__proto__" || - (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); - } - if (validateOperation) { - if (existingPathFragment === undefined) { - if (obj[key] === undefined) { - existingPathFragment = keys.slice(0, t).join("/"); - } - else if (t == len - 1) { - existingPathFragment = operation.path; - } - if (existingPathFragment !== undefined) { - validateFunction(operation, 0, document, existingPathFragment); - } - } - } - t++; - if (Array.isArray(obj)) { - if (key === "-") { - key = obj.length; - } - else { - if (validateOperation && !isInteger(key)) { - throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); - } // only parse key when it's an integer for `arr.prop` to work - else if (isInteger(key)) { - key = ~~key; - } - } - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) { - throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); - } - const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return returnValue; - } + async persistRun(_run) { } + async onRunCreate(run) { + const persistedRun = await this._convertToCreate(run, this.exampleId); + await this.client.createRun(persistedRun); + } + async onRunUpdate(run) { + const runUpdate = { + end_time: run.end_time, + error: run.error, + outputs: run.outputs, + events: run.events, + inputs: run.inputs, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + parent_run_id: run.parent_run_id, + extra: run.extra, + session_name: this.projectName, + }; + await this.client.updateRun(run.id, runUpdate); + } + getRun(id) { + return this.runMap.get(id); + } + updateFromRunTree(runTree) { + let rootRun = runTree; + const visited = new Set(); + while (rootRun.parent_run) { + if (visited.has(rootRun.id)) + break; + visited.add(rootRun.id); + if (!rootRun.parent_run) + break; + rootRun = rootRun.parent_run; + } + visited.clear(); + const queue = [rootRun]; + while (queue.length > 0) { + const current = queue.shift(); + if (!current || visited.has(current.id)) + continue; + visited.add(current.id); + // @ts-expect-error Types of property 'events' are incompatible. + this.runMap.set(current.id, current); + if (current.child_runs) { + queue.push(...current.child_runs); } - else { - if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return returnValue; + } + this.client = runTree.client ?? this.client; + this.projectName = runTree.project_name ?? this.projectName; + this.exampleId = runTree.reference_example_id ?? this.exampleId; + } + convertToRunTree(id) { + const runTreeMap = {}; + const runTreeList = []; + for (const [id, run] of this.runMap) { + // by converting the run map to a run tree, we are doing a copy + // thus, any mutation performed on the run tree will not be reflected + // back in the run map + // TODO: Stop using `this.runMap` in favour of LangSmith's `RunTree` + const runTree = new run_trees_RunTree({ + ...run, + child_runs: [], + parent_run: undefined, + // inherited properties + client: this.client, + project_name: this.projectName, + reference_example_id: this.exampleId, + tracingEnabled: true, + }); + runTreeMap[id] = runTree; + runTreeList.push([id, run.dotted_order]); + } + runTreeList.sort((a, b) => { + if (!a[1] || !b[1]) + return 0; + return a[1].localeCompare(b[1]); + }); + for (const [id] of runTreeList) { + const run = this.runMap.get(id); + const runTree = runTreeMap[id]; + if (!run || !runTree) + continue; + if (run.parent_run_id) { + const parentRunTree = runTreeMap[run.parent_run_id]; + if (parentRunTree) { + parentRunTree.child_runs.push(runTree); + runTree.parent_run = parentRunTree; } } - obj = obj[key]; - // If we have more keys in the path, but the next value isn't a non-null object, - // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. - if (validateOperation && t < len && (!obj || typeof obj !== "object")) { - throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } } + return runTreeMap[id]; } -} -/** - * Apply a full JSON Patch array on a JSON document. - * Returns the {newDocument, result} of the patch. - * It modifies the `document` object and `patch` - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. - * - * @param document The document to patch - * @param patch The patch to apply - * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return An array of `{newDocument, result}` after the patch - */ -function core_applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + static getTraceableRunTree() { + try { + return ( + // The type cast here provides forward compatibility. Old versions of LangSmith will just + // ignore the permitAbsentRunTree arg. + getCurrentRunTree(true)); + } + catch { + return undefined; } } - if (!mutateDocument) { - document = helpers_deepClone(document); - } - const results = new Array(patch.length); - for (let i = 0, length = patch.length; i < length; i++) { - // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; // in case root was replaced - } - results.newDocument = document; - return results; } + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js +const globals_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +const setGlobalAsyncLocalStorageInstance = (instance) => { + globalThis[globals_TRACING_ALS_KEY] = instance; +}; +const globals_getGlobalAsyncLocalStorageInstance = () => { + return globalThis[globals_TRACING_ALS_KEY]; +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js +/* eslint-disable @typescript-eslint/no-explicit-any */ + + +let queue; /** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the updated document. - * Suitable as a reducer. - * - * @param document The document to patch - * @param operation The operation to apply - * @return The updated document + * Creates a queue using the p-queue library. The queue is configured to + * auto-start and has a concurrency of 1, meaning it will process tasks + * one at a time. */ -function applyReducer(document, operation, index) { - const operationResult = applyOperation(document, operation); - if (operationResult.test === false) { - // failed test - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); +function createQueue() { + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + return new PQueue({ + autoStart: true, + concurrency: 1, + }); +} +function getQueue() { + if (typeof queue === "undefined") { + queue = createQueue(); } - return operationResult.newDocument; + return queue; } /** - * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. - * @param {object} operation - operation object (patch) - * @param {number} index - index of operation in the sequence - * @param {object} [document] - object where the operation is supposed to be applied - * @param {string} [existingPathFragment] - comes along with `document` + * Consume a promise, either adding it to the queue or waiting for it to resolve + * @param promiseFn Promise to consume + * @param wait Whether to wait for the promise to resolve or resolve immediately */ -function validator(operation, index, document, existingPathFragment) { - if (typeof operation !== "object" || - operation === null || - Array.isArray(operation)) { - throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); - } - else if (!objOps[operation.op]) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else if (typeof operation.path !== "string") { - throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); - } - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { - // paths that aren't empty string should start with "/" - throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); - } - else if ((operation.op === "move" || operation.op === "copy") && - typeof operation.from !== "string") { - throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); - } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - operation.value === undefined) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); - } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - hasUndefined(operation.value)) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); - } - else if (document) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { - throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); - } +async function consumeCallback(promiseFn, wait) { + if (wait === true) { + // Clear config since callbacks are not part of the root run + // Avoid using global singleton due to circuluar dependency issues + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== undefined) { + await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); } - else if (operation.op === "replace" || - operation.op === "remove" || - operation.op === "_get") { - if (operation.path !== existingPathFragment) { - throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } + else { + await promiseFn(); } - else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: undefined, - }; - var error = core_validate([existingValue], document); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { - throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); + } + else { + queue = getQueue(); + void queue.add(async () => { + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== undefined) { + await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); } - } + else { + await promiseFn(); + } + }); } } /** - * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. - * If error is encountered, returns a JsonPatchError object - * @param sequence - * @param document - * @returns {JsonPatchError|undefined} + * Waits for all promises in the queue to resolve. If the queue is + * undefined, it immediately resolves a promise. */ -function core_validate(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (document) { - //clone document and sequence so that we can safely try applying operations - core_applyPatch(helpers_deepClone(document), helpers_deepClone(sequence), externalValidator || true); - } - else { - externalValidator = externalValidator || validator; - for (var i = 0; i < sequence.length; i++) { - externalValidator(sequence[i], i, document, undefined); - } - } +function awaitAllCallbacks() { + return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js + +const callbacks_isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== undefined) { + return tracingEnabled; } - catch (e) { - if (e instanceof JsonPatchError) { - return e; - } - else { - throw e; - } + const envVars = [ + "LANGSMITH_TRACING_V2", + "LANGCHAIN_TRACING_V2", + "LANGSMITH_TRACING", + "LANGCHAIN_TRACING", + ]; + return !!envVars.find((envVar) => env_getEnvironmentVariable(envVar) === "true"); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js + + +/** + * Set a context variable. Context variables are scoped to any + * child runnables called by the current runnable, or globally if set outside + * of any runnable. + * + * @remarks + * This function is only supported in environments that support AsyncLocalStorage, + * including Node.js, Deno, and Cloudflare Workers. + * + * @example + * ```ts + * import { RunnableLambda } from "@langchain/core/runnables"; + * import { + * getContextVariable, + * setContextVariable + * } from "@langchain/core/context"; + * + * const nested = RunnableLambda.from(() => { + * // "bar" because it was set by a parent + * console.log(getContextVariable("foo")); + * + * // Override to "baz", but only for child runnables + * setContextVariable("foo", "baz"); + * + * // Now "baz", but only for child runnables + * return getContextVariable("foo"); + * }); + * + * const runnable = RunnableLambda.from(async () => { + * // Set a context variable named "foo" + * setContextVariable("foo", "bar"); + * + * const res = await nested.invoke({}); + * + * // Still "bar" since child changes do not affect parents + * console.log(getContextVariable("foo")); + * + * return res; + * }); + * + * // undefined, because context variable has not been set yet + * console.log(getContextVariable("foo")); + * + * // Final return value is "baz" + * const result = await runnable.invoke({}); + * ``` + * + * @param name The name of the context variable. + * @param value The value to set. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setContextVariable(name, value) { + // Avoid using global singleton due to circuluar dependency issues + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === undefined) { + throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); + } + const runTree = asyncLocalStorageInstance.getStore(); + const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; + contextVars[name] = value; + let newValue = {}; + if (isRunTree(runTree)) { + newValue = new RunTree(runTree); } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + newValue[_CONTEXT_VARIABLES_KEY] = contextVars; + asyncLocalStorageInstance.enterWith(newValue); } -// based on https://github.com/epoberezkin/fast-deep-equal -// MIT License -// Copyright (c) 2017 Evgeny Poberezkin -// 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. -function _areEquals(a, b) { - if (a === b) - return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) - return false; - for (i = length; i-- !== 0;) - if (!_areEquals(a[i], b[i])) - return false; - return true; - } - if (arrA != arrB) - return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length; i-- !== 0;) - if (!b.hasOwnProperty(keys[i])) - return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) - return false; - } - return true; +/** + * Get the value of a previously set context variable. Context variables + * are scoped to any child runnables called by the current runnable, + * or globally if set outside of any runnable. + * + * @remarks + * This function is only supported in environments that support AsyncLocalStorage, + * including Node.js, Deno, and Cloudflare Workers. + * + * @example + * ```ts + * import { RunnableLambda } from "@langchain/core/runnables"; + * import { + * getContextVariable, + * setContextVariable + * } from "@langchain/core/context"; + * + * const nested = RunnableLambda.from(() => { + * // "bar" because it was set by a parent + * console.log(getContextVariable("foo")); + * + * // Override to "baz", but only for child runnables + * setContextVariable("foo", "baz"); + * + * // Now "baz", but only for child runnables + * return getContextVariable("foo"); + * }); + * + * const runnable = RunnableLambda.from(async () => { + * // Set a context variable named "foo" + * setContextVariable("foo", "bar"); + * + * const res = await nested.invoke({}); + * + * // Still "bar" since child changes do not affect parents + * console.log(getContextVariable("foo")); + * + * return res; + * }); + * + * // undefined, because context variable has not been set yet + * console.log(getContextVariable("foo")); + * + * // Final return value is "baz" + * const result = await runnable.invoke({}); + * ``` + * + * @param name The name of the context variable. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getContextVariable(name) { + // Avoid using global singleton due to circuluar dependency issues + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === undefined) { + return undefined; } - return a !== a && b !== b; + const runTree = asyncLocalStorageInstance.getStore(); + return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; } +const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); +const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; +/** + * Register a callback configure hook to automatically add callback handlers to all runs. + * + * There are two ways to use this: + * + * 1. Using a context variable: + * - Set `contextVar` to specify the variable name + * - Use `setContextVariable()` to store your handler instance + * + * 2. Using an environment variable: + * - Set both `envVar` and `handlerClass` + * - The handler will be instantiated when the env var is set to "true". + * + * @example + * ```typescript + * // Method 1: Using context variable + * import { + * registerConfigureHook, + * setContextVariable + * } from "@langchain/core/context"; + * + * const tracer = new MyCallbackHandler(); + * registerConfigureHook({ + * contextVar: "my_tracer", + * }); + * setContextVariable("my_tracer", tracer); + * + * // ...run code here + * + * // Method 2: Using environment variable + * registerConfigureHook({ + * handlerClass: MyCallbackHandler, + * envVar: "MY_TRACER_ENABLED", + * }); + * process.env.MY_TRACER_ENABLED = "true"; + * + * // ...run code here + * ``` + * + * @param config Configuration object for the hook + * @param config.contextVar Name of the context variable containing the handler instance + * @param config.inheritable Whether child runs should inherit this handler + * @param config.handlerClass Optional callback handler class (required if using envVar) + * @param config.envVar Optional environment variable name to control handler activation + */ +const registerConfigureHook = (config) => { + if (config.envVar && !config.handlerClass) { + throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); + } + setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js + + -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2013-2021 Joachim Wester - * MIT license - */ -var beforeDict = new WeakMap(); -class Mirror { - constructor(obj) { - Object.defineProperty(this, "obj", { + + + + + +function parseCallbackConfigArg(arg) { + if (!arg) { + return {}; + } + else if (Array.isArray(arg) || "name" in arg) { + return { callbacks: arg }; + } + else { + return arg; + } +} +/** + * Manage callbacks from different components of LangChain. + */ +class BaseCallbackManager { + setHandler(handler) { + return this.setHandlers([handler]); + } +} +/** + * Base class for run manager in LangChain. + */ +class BaseRunManager { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + Object.defineProperty(this, "runId", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: runId }); - Object.defineProperty(this, "observers", { + Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, - value: new Map() + value: handlers }); - Object.defineProperty(this, "value", { + Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: inheritableHandlers }); - this.obj = obj; - } -} -class ObserverInfo { - constructor(callback, observer) { - Object.defineProperty(this, "callback", { + Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: tags }); - Object.defineProperty(this, "observer", { + Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: inheritableTags + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: metadata + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableMetadata + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: _parentRunId }); - this.callback = callback; - this.observer = observer; - } -} -function getMirror(obj) { - return beforeDict.get(obj); -} -function getObserverFromMirror(mirror, callback) { - return mirror.observers.get(callback); -} -function removeObserverFromMirror(mirror, observer) { - mirror.observers.delete(observer.callback); -} -/** - * Detach an observer from an object - */ -function unobserve(root, observer) { - observer.unobserve(); -} -/** - * Observes changes made to an object, which can then be retrieved using generate - */ -function observe(obj, callback) { - var patches = []; - var observer; - var mirror = getMirror(obj); - if (!mirror) { - mirror = new Mirror(obj); - beforeDict.set(obj, mirror); } - else { - const observerInfo = getObserverFromMirror(mirror, callback); - observer = observerInfo && observerInfo.observer; + get parentRunId() { + return this._parentRunId; } - if (observer) { - return observer; + async handleText(text) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); } - observer = {}; - mirror.value = _deepClone(obj); - if (callback) { - observer.callback = callback; - observer.next = null; - var dirtyCheck = () => { - duplex_generate(observer); - }; - var fastCheck = () => { - clearTimeout(observer.next); - observer.next = setTimeout(dirtyCheck); - }; - if (typeof window !== "undefined") { - //not Node - window.addEventListener("mouseup", fastCheck); - window.addEventListener("keyup", fastCheck); - window.addEventListener("mousedown", fastCheck); - window.addEventListener("keydown", fastCheck); - window.addEventListener("change", fastCheck); - } + async handleCustomEvent(eventName, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, _runId, _tags, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); } - observer.patches = patches; - observer.object = obj; - observer.unobserve = () => { - duplex_generate(observer); - clearTimeout(observer.next); - removeObserverFromMirror(mirror, observer); - if (typeof window !== "undefined") { - window.removeEventListener("mouseup", fastCheck); - window.removeEventListener("keyup", fastCheck); - window.removeEventListener("mousedown", fastCheck); - window.removeEventListener("keydown", fastCheck); - window.removeEventListener("change", fastCheck); - } - }; - mirror.observers.set(callback, new ObserverInfo(callback, observer)); - return observer; } /** - * Generate an array of patches from an observer + * Manages callbacks for retriever runs. */ -function duplex_generate(observer, invertible = false) { - var mirror = beforeDict.get(observer.object); - _generate(mirror.value, observer.object, observer.patches, "", invertible); - if (observer.patches.length) { - applyPatch(mirror.value, observer.patches); - } - var temp = observer.patches; - if (temp.length > 0) { - observer.patches = []; - if (observer.callback) { - observer.callback(temp); +class CallbackManagerForRetrieverRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); } + return manager; } - return temp; -} -// Dirty check if obj is different from mirror, generate patches and update mirror -function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) { - return; - } - if (typeof obj.toJSON === "function") { - obj = obj.toJSON(); - } - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var changed = false; - var deleted = false; - //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" - for (var t = oldKeys.length - 1; t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (helpers_hasOwnProperty(obj, key) && - !(obj[key] === undefined && - oldVal !== undefined && - Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && - oldVal != null && - typeof newVal == "object" && - newVal != null && - Array.isArray(oldVal) === Array.isArray(newVal)) { - _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); - } - else { - if (oldVal !== newVal) { - changed = true; - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(oldVal), - }); + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); + if (handler.raiseError) { + throw err; } - patches.push({ - op: "replace", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(newVal), - }); } } - } - else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(oldVal), - }); + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (error) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + if (handler.raiseError) { + throw err; + } + } } - patches.push({ - op: "remove", - path: path + "/" + escapePathComponent(key), - }); - deleted = true; // property has been deleted - } - else { - if (invertible) { - patches.push({ op: "test", path, value: mirror }); + }, handler.awaitHandlers))); + } +} +class CallbackManagerForLLMRun extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + if (handler.raiseError) { + throw err; + } + } } - patches.push({ op: "replace", path, value: obj }); - changed = true; - } + }, handler.awaitHandlers))); } - if (!deleted && newKeys.length == oldKeys.length) { - return; + async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } - for (var t = 0; t < newKeys.length; t++) { - var key = newKeys[t]; - if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== undefined) { - patches.push({ - op: "add", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(obj[key]), - }); - } + async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } } -/** - * Create an array of patches from the differences in two objects - */ -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js - - - -/** - * Default export for backwards compat - */ - - -/* harmony default export */ const fast_json_patch = ({ - ...src_core_namespaceObject, - // ...duplex, - JsonPatchError: PatchError, - deepClone: helpers_deepClone, - escapePathComponent: escapePathComponent, - unescapePathComponent: unescapePathComponent, -}); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js -const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const env_isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && - (navigator.userAgent.includes("Node.js") || - navigator.userAgent.includes("jsdom"))); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const env_isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const env_isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !env_isDeno(); -const env_getEnv = () => { - let env; - if (env_isBrowser()) { - env = "browser"; - } - else if (env_isNode()) { - env = "node"; - } - else if (env_isWebWorker()) { - env = "webworker"; +class CallbackManagerForChainRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; } - else if (env_isJsDom()) { - env = "jsdom"; + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } - else if (env_isDeno()) { - env = "deno"; + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } - else { - env = "other"; + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } - return env; -}; -let env_runtimeEnvironment; -async function env_getRuntimeEnvironment() { - if (env_runtimeEnvironment === undefined) { - const env = env_getEnv(); - env_runtimeEnvironment = { - library: "langchain-js", - runtime: env, - }; + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } - return env_runtimeEnvironment; } -function env_getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/langchain-ai/langchainjs/issues/1412 - try { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - return process.env?.[name]; - } - else if (env_isDeno()) { - return Deno?.env.get(name); - } - else { - return undefined; +class CallbackManagerForToolRun extends BaseRunManager { + getChild(tag) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); } + return manager; } - catch (e) { - return undefined; + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js - - - -/** - * Abstract class that provides a set of optional methods that can be - * overridden in derived classes to handle various events during the - * execution of a LangChain application. - */ -class BaseCallbackHandlerMethodsClass { -} -function callbackHandlerPrefersStreaming(x) { - return "lc_prefer_streaming" in x && x.lc_prefer_streaming; } /** - * Abstract base class for creating callback handlers in the LangChain - * framework. It provides a set of optional methods that can be overridden - * in derived classes to handle various events during the execution of a - * LangChain application. + * @example + * ```typescript + * const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); + * + * // Example of using LLMChain with OpenAI and a simple prompt + * const chain = new LLMChain({ + * llm: new ChatOpenAI({ temperature: 0.9 }), + * prompt, + * }); + * + * // Running the chain with a single question + * const result = await chain.call({ + * question: "What is the airspeed velocity of an unladen swallow?", + * }); + * console.log("The answer is:", result); + * ``` */ -class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { - get lc_namespace() { - return ["langchain_core", "callbacks", this.name]; - } - get lc_secrets() { - return undefined; - } - get lc_attributes() { - return undefined; - } - get lc_aliases() { - return undefined; - } - get lc_serializable_keys() { - return undefined; - } - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [ - ...this.lc_namespace, - get_lc_unique_name(this.constructor), - ]; - } - constructor(input) { +class CallbackManager extends BaseCallbackManager { + constructor(parentRunId, options) { super(); - Object.defineProperty(this, "lc_serializable", { + Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, - value: false + value: [] }); - Object.defineProperty(this, "lc_kwargs", { + Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: [] }); - Object.defineProperty(this, "ignoreLLM", { + Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, - value: false + value: [] }); - Object.defineProperty(this, "ignoreChain", { + Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, - value: false + value: [] }); - Object.defineProperty(this, "ignoreAgent", { + Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, - value: false + value: {} }); - Object.defineProperty(this, "ignoreRetriever", { + Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, - value: false + value: {} }); - Object.defineProperty(this, "ignoreCustomEvent", { + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "callback_manager" + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.handlers = options?.handlers ?? this.handlers; + this.inheritableHandlers = + options?.inheritableHandlers ?? this.inheritableHandlers; + this.tags = options?.tags ?? this.tags; + this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; + this.metadata = options?.metadata ?? this.metadata; + this.inheritableMetadata = + options?.inheritableMetadata ?? this.inheritableMetadata; + this._parentRunId = parentRunId; + } + /** + * Gets the parent run ID, if any. + * + * @returns The parent run ID. + */ + getParentRunId() { + return this._parentRunId; + } + async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + return Promise.all(prompts.map(async (prompt, idx) => { + // Can't have duplicate runs with the same run ID (if provided) + const runId_ = idx === 0 && runId ? runId : v4(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + return Promise.all(messages.map(async (messageGroup, idx) => { + // Can't have duplicate runs with the same run ID (if provided) + const runId_ = idx === 0 && runId ? runId : v4(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + if (handler.handleChatModelStart) { + await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + else if (handler.handleLLMStart) { + const messageString = getBufferString(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = v4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreChain) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } + return consumeCallback(async () => { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool, input, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreAgent) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreRetriever) { + return; + } + if (isBaseTracer(handler)) { + // Create and add run to the run map. + // We do this synchronously to avoid race conditions + // when callbacks are backgrounded. + handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleCustomEvent(eventName, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data, runId, _tags, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreCustomEvent) { + try { + await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); + } + catch (err) { + const logFunction = handler.raiseError + ? console.error + : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) { + this.inheritableHandlers.push(handler); + } + } + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); + } + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) { + this.addHandler(handler, inherit); + } + } + addTags(tags, inherit = true) { + this.removeTags(tags); // Remove duplicates + this.tags.push(...tags); + if (inherit) { + this.inheritableTags.push(...tags); + } + } + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); + } + addMetadata(metadata, inherit = true) { + this.metadata = { ...this.metadata, ...metadata }; + if (inherit) { + this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + } + } + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; + } + } + copy(additionalHandlers = [], inherit = true) { + const manager = new CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); + } + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if ( + // Prevent multiple copies of console_callback_handler + manager.handlers + .filter((h) => h.name === "console_callback_handler") + .some((h) => h.name === handler.name)) { + continue; + } + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4() + }); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); + } + // TODO: Deprecate async method in favor of this one. + static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } + else { + callbackManager = inheritableHandlers; + } + callbackManager = callbackManager.copy(Array.isArray(localHandlers) + ? localHandlers.map(ensureHandler) + : localHandlers?.handlers, false); + } + const verboseEnabled = env_getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || + options?.verbose; + const tracingV2Enabled = tracer_langchain_LangChainTracer.getTraceableRunTree()?.tracingEnabled || + callbacks_isTracingEnabled(); + const tracingEnabled = tracingV2Enabled || + (env_getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) { + callbackManager = new CallbackManager(); + } + if (verboseEnabled && + !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && + !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + const tracerV2 = new tracer_langchain_LangChainTracer(); + callbackManager.addHandler(tracerV2, true); + // handoff between langchain and langsmith/traceable + // override the parent run ID + callbackManager._parentRunId = + tracer_langchain_LangChainTracer.getTraceableRunTree()?.id ?? + callbackManager._parentRunId; + } + } + } + for (const { contextVar, inheritable = true, handlerClass, envVar, } of _getConfigureHooks()) { + const createIfNotInContext = envVar && env_getEnvironmentVariable(envVar) === "true" && handlerClass; + let handler; + const contextVarValue = contextVar !== undefined ? getContextVariable(contextVar) : undefined; + if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { + handler = contextVarValue; + } + else if (createIfNotInContext) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + handler = new handlerClass({}); + } + if (handler !== undefined) { + if (!callbackManager) { + callbackManager = new CallbackManager(); + } + if (!callbackManager.handlers.some((h) => h.name === handler.name)) { + callbackManager.addHandler(handler, inheritable); + } + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + return callbackManager; + } +} +function ensureHandler(handler) { + if ("name" in handler) { + return handler; + } + return BaseCallbackHandler.fromMethods(handler); +} +/** + * @deprecated Use [`traceable`](https://docs.smith.langchain.com/observability/how_to_guides/tracing/annotate_code) + * from "langsmith" instead. + */ +class TraceGroup { + constructor(groupName, options) { + Object.defineProperty(this, "groupName", { enumerable: true, configurable: true, writable: true, - value: false + value: groupName }); - Object.defineProperty(this, "raiseError", { + Object.defineProperty(this, "options", { enumerable: true, configurable: true, writable: true, - value: false + value: options }); - Object.defineProperty(this, "awaitHandlers", { + Object.defineProperty(this, "runManager", { enumerable: true, configurable: true, writable: true, - value: env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + value: void 0 }); - this.lc_kwargs = input || {}; - if (input) { - this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; - this.ignoreChain = input.ignoreChain ?? this.ignoreChain; - this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; - this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; - this.ignoreCustomEvent = - input.ignoreCustomEvent ?? this.ignoreCustomEvent; - this.raiseError = input.raiseError ?? this.raiseError; - this.awaitHandlers = - this.raiseError || (input._awaitHandler ?? this.awaitHandlers); - } } - copy() { - return new this.constructor(this); + async getTraceGroupCallbackManager(group_name, inputs, options) { + const cb = new LangChainTracer(options); + const cm = await CallbackManager.configure([cb]); + const runManager = await cm?.handleChainStart({ + lc: 1, + type: "not_implemented", + id: ["langchain", "callbacks", "groups", group_name], + }, inputs ?? {}); + if (!runManager) { + throw new Error("Failed to create run group callback manager."); + } + return runManager; } - toJSON() { - return Serializable.prototype.toJSON.call(this); + async start(inputs) { + if (!this.runManager) { + this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); + } + return this.runManager.getChild(); } - toJSONNotImplemented() { - return Serializable.prototype.toJSONNotImplemented.call(this); + async error(err) { + if (this.runManager) { + await this.runManager.handleChainError(err); + this.runManager = undefined; + } } - static fromMethods(methods) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: v4() - }); - Object.assign(this, methods); - } + async end(output) { + if (this.runManager) { + await this.runManager.handleChainEnd(output ?? {}); + this.runManager = undefined; } - return new Handler(); } } -const isBaseCallbackHandler = (x) => { - const callbackHandler = x; - return (callbackHandler !== undefined && - typeof callbackHandler.copy === "function" && - typeof callbackHandler.name === "string" && - typeof callbackHandler.awaitHandlers === "boolean"); -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js - // eslint-disable-next-line @typescript-eslint/no-explicit-any -function _coerceToDict(value, defaultKey) { +function manager_coerceToDict(value, defaultKey) { return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; } -function base_stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function base_convertToDottedOrderFormat(epoch, runId, executionOrder) { - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return (base_stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +async function traceAsGroup(groupOptions, enclosedCode, ...args) { + const traceGroup = new TraceGroup(groupOptions.name, groupOptions); + const callbackManager = await traceGroup.start({ ...args }); + try { + const result = await enclosedCode(callbackManager, ...args); + await traceGroup.end(manager_coerceToDict(result, "output")); + return result; + } + catch (err) { + await traceGroup.error(err); + throw err; + } } -function isBaseTracer(x) { - return typeof x._addRunToRunMap === "function"; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js +/* eslint-disable @typescript-eslint/no-explicit-any */ + + + +class async_local_storage_MockAsyncLocalStorage { + getStore() { + return undefined; + } + run(_store, callback) { + return callback(); + } + enterWith(_store) { + return undefined; + } } -class BaseTracer extends BaseCallbackHandler { - constructor(_fields) { - super(...arguments); - Object.defineProperty(this, "runMap", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); +const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); +const LC_CHILD_KEY = Symbol.for("lc:child_config"); +class async_local_storage_AsyncLocalStorageProvider { + getInstance() { + return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; } - copy() { - return this; + getRunnableConfig() { + const storage = this.getInstance(); + // this has the runnable config + // which means that we should also have an instance of a LangChainTracer + // with the run map prepopulated + return storage.getStore()?.extra?.[LC_CHILD_KEY]; } - stringifyError(error) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - return error.message + (error?.stack ? `\n\n${error.stack}` : ""); + runWithConfig(config, callback, avoidCreatingRootRunTree) { + const callbackManager = CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); + const storage = this.getInstance(); + const previousValue = storage.getStore(); + const parentRunId = callbackManager?.getParentRunId(); + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); + let runTree; + if (langChainTracer && parentRunId) { + runTree = langChainTracer.convertToRunTree(parentRunId); } - if (typeof error === "string") { - return error; + else if (!avoidCreatingRootRunTree) { + runTree = new run_trees_RunTree({ + name: "", + tracingEnabled: false, + }); } - return `${error}`; + if (runTree) { + runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config }; + } + if (previousValue !== undefined && + previousValue[globals_CONTEXT_VARIABLES_KEY] !== undefined) { + if (runTree === undefined) { + runTree = {}; + } + runTree[globals_CONTEXT_VARIABLES_KEY] = + previousValue[globals_CONTEXT_VARIABLES_KEY]; + } + return storage.run(runTree, callback); } - _addChildRun(parentRun, childRun) { - parentRun.child_runs.push(childRun); + initializeGlobalInstance(instance) { + if (globals_getGlobalAsyncLocalStorageInstance() === undefined) { + setGlobalAsyncLocalStorageInstance(instance); + } } - _addRunToRunMap(run) { - const currentDottedOrder = base_convertToDottedOrderFormat(run.start_time, run.id, run.execution_order); - const storedRun = { ...run }; - if (storedRun.parent_run_id !== undefined) { - const parentRun = this.runMap.get(storedRun.parent_run_id); - if (parentRun) { - this._addChildRun(parentRun, storedRun); - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); - storedRun.trace_id = parentRun.trace_id; - if (parentRun.dotted_order !== undefined) { - storedRun.dotted_order = [ - parentRun.dotted_order, - currentDottedOrder, - ].join("."); +} +const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js + + +const DEFAULT_RECURSION_LIMIT = 25; +async function getCallbackManagerForConfig(config) { + return CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); +} +function mergeConfigs(...configs) { + // We do not want to call ensureConfig on the empty state here as this may cause + // double loading of callbacks if async local storage is being used. + const copy = {}; + for (const options of configs.filter((c) => !!c)) { + for (const key of Object.keys(options)) { + if (key === "metadata") { + copy[key] = { ...copy[key], ...options[key] }; + } + else if (key === "tags") { + const baseKeys = copy[key] ?? []; + copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; + } + else if (key === "configurable") { + copy[key] = { ...copy[key], ...options[key] }; + } + else if (key === "timeout") { + if (copy.timeout === undefined) { + copy.timeout = options.timeout; } - else { - // This can happen naturally for callbacks added within a run - // console.debug(`Parent run with UUID ${storedRun.parent_run_id} has no dotted order.`); + else if (options.timeout !== undefined) { + copy.timeout = Math.min(copy.timeout, options.timeout); + } + } + else if (key === "signal") { + if (copy.signal === undefined) { + copy.signal = options.signal; + } + else if (options.signal !== undefined) { + if ("any" in AbortSignal) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + copy.signal = AbortSignal.any([ + copy.signal, + options.signal, + ]); + } + else { + copy.signal = options.signal; + } + } + } + else if (key === "callbacks") { + const baseCallbacks = copy.callbacks; + const providedCallbacks = options.callbacks; + // callbacks can be either undefined, Array or manager + // so merging two callbacks values has 6 cases + if (Array.isArray(providedCallbacks)) { + if (!baseCallbacks) { + copy.callbacks = providedCallbacks; + } + else if (Array.isArray(baseCallbacks)) { + copy.callbacks = baseCallbacks.concat(providedCallbacks); + } + else { + // baseCallbacks is a manager + const manager = baseCallbacks.copy(); + for (const callback of providedCallbacks) { + manager.addHandler(ensureHandler(callback), true); + } + copy.callbacks = manager; + } + } + else if (providedCallbacks) { + // providedCallbacks is a manager + if (!baseCallbacks) { + copy.callbacks = providedCallbacks; + } + else if (Array.isArray(baseCallbacks)) { + const manager = providedCallbacks.copy(); + for (const callback of baseCallbacks) { + manager.addHandler(ensureHandler(callback), true); + } + copy.callbacks = manager; + } + else { + // baseCallbacks is also a manager + copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { + handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), + inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), + tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), + inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), + metadata: { + ...baseCallbacks.metadata, + ...providedCallbacks.metadata, + }, + }); + } } } else { - // This can happen naturally for callbacks added within a run - // console.debug( - // `Parent run with UUID ${storedRun.parent_run_id} not found.` - // ); + const typedKey = key; + copy[typedKey] = options[typedKey] ?? copy[typedKey]; } } - else { - storedRun.trace_id = storedRun.id; - storedRun.dotted_order = currentDottedOrder; + } + return copy; +} +const PRIMITIVES = new Set(["string", "number", "boolean"]); +/** + * Ensure that a passed config is an object with all required keys present. + */ +function ensureConfig(config) { + const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); + let empty = { + tags: [], + metadata: {}, + recursionLimit: 25, + runId: undefined, + }; + if (implicitConfig) { + // Don't allow runId and runName to be loaded implicitly, as this can cause + // child runs to improperly inherit their parents' run ids. + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { runId, runName, ...rest } = implicitConfig; + empty = Object.entries(rest).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (currentConfig, [key, value]) => { + if (value !== undefined) { + // eslint-disable-next-line no-param-reassign + currentConfig[key] = value; + } + return currentConfig; + }, empty); + } + if (config) { + empty = Object.entries(config).reduce( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (currentConfig, [key, value]) => { + if (value !== undefined) { + // eslint-disable-next-line no-param-reassign + currentConfig[key] = value; + } + return currentConfig; + }, empty); + } + if (empty?.configurable) { + for (const key of Object.keys(empty.configurable)) { + if (PRIMITIVES.has(typeof empty.configurable[key]) && + !empty.metadata?.[key]) { + if (!empty.metadata) { + empty.metadata = {}; + } + empty.metadata[key] = empty.configurable[key]; + } } - this.runMap.set(storedRun.id, storedRun); - return storedRun; } - async _endTrace(run) { - const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); - if (parentRun) { - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + if (empty.timeout !== undefined) { + if (empty.timeout <= 0) { + throw new Error("Timeout must be a positive number"); } - else { - await this.persistRun(run); + const timeoutSignal = AbortSignal.timeout(empty.timeout); + if (empty.signal !== undefined) { + if ("any" in AbortSignal) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + } } - this.runMap.delete(run.id); - await this.onRunUpdate?.(run); - } - _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); - // If a run has no parent then execution order is 1 - if (!parentRun) { - return 1; + else { + empty.signal = timeoutSignal; } - return parentRun.child_execution_order + 1; - } - /** - * Create and add a run to the run map for LLM start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata - ? { ...extraParams, metadata } - : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { prompts }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); - } - async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; + delete empty.timeout; } - /** - * Create and add a run to the run map for chat model start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata - ? { ...extraParams, metadata } - : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { messages }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); + return empty; +} +/** + * Helper function that patches runnable configs with updated properties. + */ +function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId, } = {}) { + const newConfig = ensureConfig(config); + if (callbacks !== undefined) { + /** + * If we're replacing callbacks we need to unset runName + * since that should apply only to the same run as the original callbacks + */ + delete newConfig.runName; + newConfig.callbacks = callbacks; } - async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; + if (recursionLimit !== undefined) { + newConfig.recursionLimit = recursionLimit; } - async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); - } - run.end_time = Date.now(); - run.outputs = output; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - run.extra = { ...run.extra, ...extraParams }; - await this.onLLMEnd?.(run); - await this._endTrace(run); - return run; + if (maxConcurrency !== undefined) { + newConfig.maxConcurrency = maxConcurrency; } - async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error("No LLM run to end."); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - run.extra = { ...run.extra, ...extraParams }; - await this.onLLMError?.(run); - await this._endTrace(run); - return run; + if (runName !== undefined) { + newConfig.runName = runName; } - /** - * Create and add a run to the run map for chain start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? chain.id[chain.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: chain, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs, - execution_order, - child_execution_order: execution_order, - run_type: runType ?? "chain", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); + if (configurable !== undefined) { + newConfig.configurable = { ...newConfig.configurable, ...configurable }; } - async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const run = this.runMap.get(runId) ?? - this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); - await this.onRunCreate?.(run); - await this.onChainStart?.(run); - return run; + if (runId !== undefined) { + delete newConfig.runId; } - async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); + return newConfig; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function pickRunnableConfigKeys(config) { + return config + ? { + configurable: config.configurable, + recursionLimit: config.recursionLimit, + callbacks: config.callbacks, + tags: config.tags, + metadata: config.metadata, + maxConcurrency: config.maxConcurrency, + timeout: config.timeout, + signal: config.signal, } - run.end_time = Date.now(); - run.outputs = _coerceToDict(outputs, "output"); - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), + : undefined; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js +async function raceWithSignal(promise, signal) { + if (signal === undefined) { + return promise; + } + let listener; + return Promise.race([ + promise.catch((err) => { + if (!signal?.aborted) { + throw err; + } + else { + return undefined; + } + }), + new Promise((_, reject) => { + listener = () => { + reject(new Error("Aborted")); + }; + signal.addEventListener("abort", listener); + // Must be here inside the promise to avoid a race condition + if (signal.aborted) { + reject(new Error("Aborted")); + } + }), + ]).finally(() => signal.removeEventListener("abort", listener)); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js + + + +/* + * Support async iterator syntax for ReadableStreams in all environments. + * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +class IterableReadableStream extends ReadableStream { + constructor() { + super(...arguments); + Object.defineProperty(this, "reader", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - if (kwargs?.inputs !== undefined) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + ensureReader() { + if (!this.reader) { + this.reader = this.getReader(); } - await this.onChainEnd?.(run); - await this._endTrace(run); - return run; } - async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); - if (!run) { - throw new Error("No chain run to end."); + async next() { + this.ensureReader(); + try { + const result = await this.reader.read(); + if (result.done) { + this.reader.releaseLock(); // release lock when stream becomes closed + return { + done: true, + value: undefined, + }; + } + else { + return { + done: false, + value: result.value, + }; + } } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - if (kwargs?.inputs !== undefined) { - run.inputs = _coerceToDict(kwargs.inputs, "input"); + catch (e) { + this.reader.releaseLock(); // release lock when stream becomes errored + throw e; } - await this.onChainError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for tool start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? tool.id[tool.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: tool, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { input }, - execution_order, - child_execution_order: execution_order, - run_type: "tool", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); } - async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onToolStart?.(run); - return run; + async return() { + this.ensureReader(); + // If wrapped in a Node stream, cancel is already called. + if (this.locked) { + const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet + this.reader.releaseLock(); // release lock first + await cancelPromise; // now await it + } + return { done: true, value: undefined }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleToolEnd(output, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); + async throw(e) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet + this.reader.releaseLock(); // release lock first + await cancelPromise; // now await it } - run.end_time = Date.now(); - run.outputs = { output }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onToolEnd?.(run); - await this._endTrace(run); - return run; + throw e; } - async handleToolError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "tool") { - throw new Error("No tool run to end"); - } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), + [Symbol.asyncIterator]() { + return this; + } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not present in Node 18 types, required in latest Node 22 + async [Symbol.asyncDispose]() { + await this.return(); + } + static fromReadableStream(stream) { + // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream + const reader = stream.getReader(); + return new IterableReadableStream({ + start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + // When no more data needs to be consumed, close the stream + if (done) { + controller.close(); + return; + } + // Enqueue the next data chunk into our target stream + controller.enqueue(value); + return pump(); + }); + } + }, + cancel() { + reader.releaseLock(); + }, }); - await this.onToolError?.(run); - await this._endTrace(run); - return run; } - async handleAgentAction(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - const agentRun = run; - agentRun.actions = agentRun.actions || []; - agentRun.actions.push(action); - agentRun.events.push({ - name: "agent_action", - time: new Date().toISOString(), - kwargs: { action }, + static fromAsyncGenerator(generator) { + return new IterableReadableStream({ + async pull(controller) { + const { value, done } = await generator.next(); + // When no more data needs to be consumed, close the stream + if (done) { + controller.close(); + } + // Fix: `else if (value)` will hang the streaming when nullish value (e.g. empty string) is pulled + controller.enqueue(value); + }, + async cancel(reason) { + await generator.return(reason); + }, }); - await this.onAgentAction?.(run); } - async handleAgentEnd(action, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; +} +function atee(iter, length = 2) { + const buffers = Array.from({ length }, () => []); + return buffers.map(async function* makeIter(buffer) { + while (true) { + if (buffer.length === 0) { + const result = await iter.next(); + for (const buffer of buffers) { + buffer.push(result); + } + } + else if (buffer[0].done) { + return; + } + else { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + yield buffer.shift().value; + } } - run.events.push({ - name: "agent_end", - time: new Date().toISOString(), - kwargs: { action }, - }); - await this.onAgentEnd?.(run); + }); +} +function concat(first, second) { + if (Array.isArray(first) && Array.isArray(second)) { + return first.concat(second); } - /** - * Create and add a run to the run map for retriever start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? retriever.id[retriever.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: retriever, - events: [ - { - name: "start", - time: new Date(start_time).toISOString(), - }, - ], - inputs: { query }, - execution_order, - child_execution_order: execution_order, - run_type: "retriever", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [], - }; - return this._addRunToRunMap(run); + else if (typeof first === "string" && typeof second === "string") { + return (first + second); } - async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? - this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onRetrieverStart?.(run); - return run; + else if (typeof first === "number" && typeof second === "number") { + return (first + second); } - async handleRetrieverEnd(documents, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); - } - run.end_time = Date.now(); - run.outputs = { documents }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString(), - }); - await this.onRetrieverEnd?.(run); - await this._endTrace(run); - return run; + else if ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "concat" in first && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + typeof first.concat === "function") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return first.concat(second); } - async handleRetrieverError(error, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "retriever") { - throw new Error("No retriever run to end"); + else if (typeof first === "object" && typeof second === "object") { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const chunk = { ...first }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + for (const [key, value] of Object.entries(second)) { + if (key in chunk && !Array.isArray(chunk[key])) { + chunk[key] = concat(chunk[key], value); + } + else { + chunk[key] = value; + } } - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString(), - }); - await this.onRetrieverError?.(run); - await this._endTrace(run); - return run; + return chunk; } - async handleText(text, runId) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "chain") { - return; - } - run.events.push({ - name: "text", - time: new Date().toISOString(), - kwargs: { text }, + else { + throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); + } +} +class AsyncGeneratorWithSetup { + constructor(params) { + Object.defineProperty(this, "generator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "setup", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "config", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "signal", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "firstResult", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "firstResultUsed", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + this.generator = params.generator; + this.config = params.config; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.signal = params.signal ?? this.config?.signal; + // setup is a promise that resolves only after the first iterator value + // is available. this is useful when setup of several piped generators + // needs to happen in logical order, ie. in the order in which input to + // to each generator is available. + this.setup = new Promise((resolve, reject) => { + void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => { + this.firstResult = params.generator.next(); + if (params.startSetup) { + this.firstResult.then(params.startSetup).then(resolve, reject); + } + else { + this.firstResult.then((_result) => resolve(undefined), reject); + } + }, true); }); - await this.onText?.(run); } - async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.runMap.get(runId); - if (!run || run?.run_type !== "llm") { - throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + async next(...args) { + this.signal?.throwIfAborted(); + if (!this.firstResultUsed) { + this.firstResultUsed = true; + return this.firstResult; } - run.events.push({ - name: "new_token", - time: new Date().toISOString(), - kwargs: { token, idx, chunk: fields?.chunk }, - }); - await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); - return run; + return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal + ? async () => { + return raceWithSignal(this.generator.next(...args), this.signal); + } + : async () => { + return this.generator.next(...args); + }, true); + } + async return(value) { + return this.generator.return(value); + } + async throw(e) { + return this.generator.throw(e); + } + [Symbol.asyncIterator]() { + return this; } + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore Not present in Node 18 types, required in latest Node 22 + async [Symbol.asyncDispose]() { + await this.return(); + } +} +async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { + const gen = new AsyncGeneratorWithSetup({ + generator, + startSetup, + signal, + }); + const setup = await gen.setup; + return { output: to(gen, setup, ...args), setup }; } -// EXTERNAL MODULE: ./node_modules/@langchain/core/node_modules/ansi-styles/index.js -var ansi_styles = __nccwpck_require__(2227); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js -function wrap(style, text) { - return `${style.open}${text}${style.close}`; -} -function tryJsonStringify(obj, fallback) { - try { - return JSON.stringify(obj, null, 2); + + +/** + * List of jsonpatch JSONPatchOperations, which describe how to create the run state + * from an empty dict. This is the minimal representation of the log, designed to + * be serialized as JSON and sent over the wire to reconstruct the log on the other + * side. Reconstruction of the state can be done with any jsonpatch-compliant library, + * see https://jsonpatch.com for more information. + */ +class RunLogPatch { + constructor(fields) { + Object.defineProperty(this, "ops", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.ops = fields.ops ?? []; } - catch (err) { - return fallback; + concat(other) { + const ops = this.ops.concat(other.ops); + const states = core_applyPatch({}, ops); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunLog({ + ops, + state: states[states.length - 1].newDocument, + }); } } -function formatKVMapItem(value) { - if (typeof value === "string") { - return value.trim(); +class RunLog extends RunLogPatch { + constructor(fields) { + super(fields); + Object.defineProperty(this, "state", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.state = fields.state; } - if (value === null || value === undefined) { - return value; + concat(other) { + const ops = this.ops.concat(other.ops); + const states = core_applyPatch(this.state, other.ops); + return new RunLog({ ops, state: states[states.length - 1].newDocument }); } - return tryJsonStringify(value, value.toString()); -} -function elapsed(run) { - if (!run.end_time) - return ""; - const elapsed = run.end_time - run.start_time; - if (elapsed < 1000) { - return `${elapsed}ms`; + static fromRunLogPatch(patch) { + const states = core_applyPatch({}, patch.ops); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunLog({ + ops: patch.ops, + state: states[states.length - 1].newDocument, + }); } - return `${(elapsed / 1000).toFixed(2)}s`; } -const { color } = ansi_styles; +const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; /** - * A tracer that logs all events to the console. It extends from the - * `BaseTracer` class and overrides its methods to provide custom logging - * functionality. - * @example - * ```typescript + * Extract standardized inputs from a run. * - * const llm = new ChatAnthropic({ - * temperature: 0, - * tags: ["example", "callbacks", "constructor"], - * callbacks: [new ConsoleCallbackHandler()], - * }); + * Standardizes the inputs based on the type of the runnable used. * - * ``` + * @param run - Run object + * @param schemaFormat - The schema format to use. + * + * @returns Valid inputs are only dict. By conventions, inputs always represented + * invocation using named arguments. + * A null means that the input is not yet known! */ -class ConsoleCallbackHandler extends BaseTracer { - constructor() { - super(...arguments); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "console_callback_handler" - }); +async function _getStandardizedInputs(run, schemaFormat) { + if (schemaFormat === "original") { + throw new Error("Do not assign inputs with original schema drop the key for now. " + + "When inputs are added to streamLog they should be added with " + + "standardized schema for streaming events."); } - /** - * Method used to persist the run. In this case, it simply returns a - * resolved promise as there's no persistence logic. - * @param _run The run to persist. - * @returns A resolved promise. - */ - persistRun(_run) { - return Promise.resolve(); + const { inputs } = run; + if (["retriever", "llm", "prompt"].includes(run.run_type)) { + return inputs; } - // utility methods - /** - * Method used to get all the parent runs of a given run. - * @param run The run whose parents are to be retrieved. - * @returns An array of parent runs. - */ - getParents(run) { - const parents = []; - let currentRun = run; - while (currentRun.parent_run_id) { - const parent = this.runMap.get(currentRun.parent_run_id); - if (parent) { - parents.push(parent); - currentRun = parent; - } - else { - break; - } - } - return parents; + if (Object.keys(inputs).length === 1 && inputs?.input === "") { + return undefined; } - /** - * Method used to get a string representation of the run's lineage, which - * is used in logging. - * @param run The run whose lineage is to be retrieved. - * @returns A string representation of the run's lineage. - */ - getBreadcrumbs(run) { - const parents = this.getParents(run).reverse(); - const string = [...parents, run] - .map((parent, i, arr) => { - const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; - return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; - }) - .join(" > "); - return wrap(color.grey, string); + // new style chains + // These nest an additional 'input' key inside the 'inputs' to make sure + // the input is always a dict. We need to unpack and user the inner value. + // We should try to fix this in Runnables and callbacks/tracers + // Runnables should be using a null type here not a placeholder + // dict. + return inputs.input; +} +async function _getStandardizedOutputs(run, schemaFormat) { + const { outputs } = run; + if (schemaFormat === "original") { + // Return the old schema, without standardizing anything + return outputs; } - // logging methods - /** - * Method used to log the start of a chain run. - * @param run The chain run that has started. - * @returns void - */ - onChainStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + if (["retriever", "llm", "prompt"].includes(run.run_type)) { + return outputs; } - /** - * Method used to log the end of a chain run. - * @param run The chain run that has ended. - * @returns void - */ - onChainEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + // TODO: Remove this hacky check + if (outputs !== undefined && + Object.keys(outputs).length === 1 && + outputs?.output !== undefined) { + return outputs.output; } - /** - * Method used to log any errors of a chain run. - * @param run The chain run that has errored. - * @returns void - */ - onChainError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + return outputs; +} +function isChatGenerationChunk(x) { + return x !== undefined && x.message !== undefined; +} +/** + * Class that extends the `BaseTracer` class from the + * `langchain.callbacks.tracers.base` module. It represents a callback + * handler that logs the execution of runs and emits `RunLog` instances to a + * `RunLogStream`. + */ +class LogStreamCallbackHandler extends BaseTracer { + constructor(fields) { + super({ _awaitHandler: true, ...fields }); + Object.defineProperty(this, "autoClose", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "includeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "includeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_schemaFormat", { + enumerable: true, + configurable: true, + writable: true, + value: "original" + }); + Object.defineProperty(this, "rootId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "keyMapByRunId", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "counterMapByRunName", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "log_stream_tracer" + }); + Object.defineProperty(this, "lc_prefer_streaming", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); } - /** - * Method used to log the start of an LLM run. - * @param run The LLM run that has started. - * @returns void - */ - onLLMStart(run) { - const crumbs = this.getBreadcrumbs(run); - const inputs = "prompts" in run.inputs - ? { prompts: run.inputs.prompts.map((p) => p.trim()) } - : run.inputs; - console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + [Symbol.asyncIterator]() { + return this.receiveStream; } - /** - * Method used to log the end of an LLM run. - * @param run The LLM run that has ended. - * @returns void - */ - onLLMEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); + async persistRun(_run) { + // This is a legacy method only called once for an entire run tree + // and is therefore not useful here } - /** - * Method used to log any errors of an LLM run. - * @param run The LLM run that has errored. - * @returns void - */ - onLLMError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + _includeRun(run) { + if (run.id === this.rootId) { + return false; + } + const runTags = run.tags ?? []; + let include = this.includeNames === undefined && + this.includeTags === undefined && + this.includeTypes === undefined; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(run.run_type); + } + if (this.includeTags !== undefined) { + include = + include || + runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(run.run_type); + } + if (this.excludeTags !== undefined) { + include = + include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + } + return include; } - /** - * Method used to log the start of a tool run. - * @param run The tool run that has started. - * @returns void - */ - onToolStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); + async *tapOutputIterable(runId, output) { + // Tap an output async iterator to stream its values to the log. + for await (const chunk of output) { + // root run is handled in .streamLog() + if (runId !== this.rootId) { + // if we can't find the run silently ignore + // eg. because this run wasn't included in the log + const key = this.keyMapByRunId[runId]; + if (key) { + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${key}/streamed_output/-`, + value: chunk, + }, + ], + })); + } + } + yield chunk; + } + } + async onRunCreate(run) { + if (this.rootId === undefined) { + this.rootId = run.id; + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "replace", + path: "", + value: { + id: run.id, + name: run.name, + type: run.run_type, + streamed_output: [], + final_output: undefined, + logs: {}, + }, + }, + ], + })); + } + if (!this._includeRun(run)) { + return; + } + if (this.counterMapByRunName[run.name] === undefined) { + this.counterMapByRunName[run.name] = 0; + } + this.counterMapByRunName[run.name] += 1; + const count = this.counterMapByRunName[run.name]; + this.keyMapByRunId[run.id] = + count === 1 ? run.name : `${run.name}:${count}`; + const logEntry = { + id: run.id, + name: run.name, + type: run.run_type, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + start_time: new Date(run.start_time).toISOString(), + streamed_output: [], + streamed_output_str: [], + final_output: undefined, + end_time: undefined, + }; + if (this._schemaFormat === "streaming_events") { + logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); + } + await this.writer.write(new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${this.keyMapByRunId[run.id]}`, + value: logEntry, + }, + ], + })); } - /** - * Method used to log the end of a tool run. - * @param run The tool run that has ended. - * @returns void - */ - onToolEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + async onRunUpdate(run) { + try { + const runName = this.keyMapByRunId[run.id]; + if (runName === undefined) { + return; + } + const ops = []; + if (this._schemaFormat === "streaming_events") { + ops.push({ + op: "replace", + path: `/logs/${runName}/inputs`, + value: await _getStandardizedInputs(run, this._schemaFormat), + }); + } + ops.push({ + op: "add", + path: `/logs/${runName}/final_output`, + value: await _getStandardizedOutputs(run, this._schemaFormat), + }); + if (run.end_time !== undefined) { + ops.push({ + op: "add", + path: `/logs/${runName}/end_time`, + value: new Date(run.end_time).toISOString(), + }); + } + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } + finally { + if (run.id === this.rootId) { + const patch = new RunLogPatch({ + ops: [ + { + op: "replace", + path: "/final_output", + value: await _getStandardizedOutputs(run, this._schemaFormat), + }, + ], + }); + await this.writer.write(patch); + if (this.autoClose) { + await this.writer.close(); + } + } + } } - /** - * Method used to log any errors of a tool run. - * @param run The tool run that has errored. - * @returns void - */ - onToolError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + async onLLMNewToken(run, token, kwargs) { + const runName = this.keyMapByRunId[run.id]; + if (runName === undefined) { + return; + } + // TODO: Remove hack + const isChatModel = run.inputs.messages !== undefined; + let streamedOutputValue; + if (isChatModel) { + if (isChatGenerationChunk(kwargs?.chunk)) { + streamedOutputValue = kwargs?.chunk; + } + else { + streamedOutputValue = new ai_AIMessageChunk({ + id: `run-${run.id}`, + content: token, + }); + } + } + else { + streamedOutputValue = token; + } + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: `/logs/${runName}/streamed_output_str/-`, + value: token, + }, + { + op: "add", + path: `/logs/${runName}/streamed_output/-`, + value: streamedOutputValue, + }, + ], + }); + await this.writer.write(patch); } - /** - * Method used to log the start of a retriever run. - * @param run The retriever run that has started. - * @returns void - */ - onRetrieverStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js +const RUN_KEY = "__run"; +/** + * Chunk of a single generation. Used for streaming. + */ +class GenerationChunk { + constructor(fields) { + Object.defineProperty(this, "text", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "generationInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.text = fields.text; + this.generationInfo = fields.generationInfo; } - /** - * Method used to log the end of a retriever run. - * @param run The retriever run that has ended. - * @returns void - */ - onRetrieverEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + concat(chunk) { + return new GenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo, + }, + }); } - /** - * Method used to log any errors of a retriever run. - * @param run The retriever run that has errored. - * @returns void - */ - onRetrieverError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); +} +class ChatGenerationChunk extends GenerationChunk { + constructor(fields) { + super(fields); + Object.defineProperty(this, "message", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.message = fields.message; } - /** - * Method used to log the action selected by the agent. - * @param run The run in which the agent action occurred. - * @returns void - */ - onAgentAction(run) { - const agentRun = run; - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + concat(chunk) { + return new ChatGenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo, + }, + message: this.message.concat(chunk.message), + }); } } -;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js -;// CONCATENATED MODULE: ./node_modules/langsmith/index.js -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js -let client; -const getDefaultLangChainClientSingleton = () => { - if (client === undefined) { - const clientParams = env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" - ? { - // LangSmith has its own backgrounding system - blockOnRootRunFinalization: true, - } - : {}; - client = new Client(clientParams); +function assignName({ name, serialized, }) { + if (name !== undefined) { + return name; } - return client; -}; -const setDefaultLangChainClientSingleton = (newClient) => { - client = newClient; -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js - - - - - -class tracer_langchain_LangChainTracer extends BaseTracer { - constructor(fields = {}) { - super(fields); - Object.defineProperty(this, "name", { + if (serialized?.name !== undefined) { + return serialized.name; + } + else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) { + return serialized.id[serialized.id.length - 1]; + } + return "Unnamed"; +} +const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; +/** + * Class that extends the `BaseTracer` class from the + * `langchain.callbacks.tracers.base` module. It represents a callback + * handler that logs the execution of runs and emits `RunLog` instances to a + * `RunLogStream`. + */ +class EventStreamCallbackHandler extends BaseTracer { + constructor(fields) { + super({ _awaitHandler: true, ...fields }); + Object.defineProperty(this, "autoClose", { enumerable: true, configurable: true, writable: true, - value: "langchain_tracer" + value: true }); - Object.defineProperty(this, "projectName", { + Object.defineProperty(this, "includeNames", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "exampleId", { + Object.defineProperty(this, "includeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "client", { + Object.defineProperty(this, "includeTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); - const { exampleId, projectName, client } = fields; - this.projectName = - projectName ?? - env_getEnvironmentVariable("LANGCHAIN_PROJECT") ?? - env_getEnvironmentVariable("LANGCHAIN_SESSION"); - this.exampleId = exampleId; - this.client = client ?? getDefaultLangChainClientSingleton(); - const traceableTree = tracer_langchain_LangChainTracer.getTraceableRunTree(); - if (traceableTree) { - this.updateFromRunTree(traceableTree); + Object.defineProperty(this, "excludeNames", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTypes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "runInfoMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "tappedPromises", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "transformStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "writer", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "receiveStream", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "event_stream_tracer" + }); + Object.defineProperty(this, "lc_prefer_streaming", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) { + // This is a legacy method only called once for an entire run tree + // and is therefore not useful here + } + _includeRun(run) { + const runTags = run.tags ?? []; + let include = this.includeNames === undefined && + this.includeTags === undefined && + this.includeTypes === undefined; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(run.name); + } + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(run.runType); + } + if (this.includeTags !== undefined) { + include = + include || + runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + } + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(run.name); + } + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(run.runType); + } + if (this.excludeTags !== undefined) { + include = + include && runTags.every((tag) => !this.excludeTags?.includes(tag)); } + return include; } - async _convertToCreate(run, example_id = undefined) { - return { - ...run, - extra: { - ...run.extra, - runtime: await env_getRuntimeEnvironment(), - }, - child_runs: undefined, - session_name: this.projectName, - reference_example_id: run.parent_run_id ? undefined : example_id, - }; + async *tapOutputIterable(runId, outputStream) { + const firstChunk = await outputStream.next(); + if (firstChunk.done) { + return; + } + const runInfo = this.runInfoMap.get(runId); + // Run has finished, don't issue any stream events. + // An example of this is for runnables that use the default + // implementation of .stream(), which delegates to .invoke() + // and calls .onChainEnd() before passing it to the iterator. + if (runInfo === undefined) { + yield firstChunk.value; + return; + } + // Match format from handlers below + function _formatOutputChunk(eventType, data) { + if (eventType === "llm" && typeof data === "string") { + return new GenerationChunk({ text: data }); + } + return data; + } + let tappedPromise = this.tappedPromises.get(runId); + // if we are the first to tap, issue stream events + if (tappedPromise === undefined) { + let tappedPromiseResolver; + tappedPromise = new Promise((resolve) => { + tappedPromiseResolver = resolve; + }); + this.tappedPromises.set(runId, tappedPromise); + try { + const event = { + event: `on_${runInfo.runType}_stream`, + run_id: runId, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + data: {}, + }; + await this.send({ + ...event, + data: { + chunk: _formatOutputChunk(runInfo.runType, firstChunk.value), + }, + }, runInfo); + yield firstChunk.value; + for await (const chunk of outputStream) { + // Don't yield tool and retriever stream events + if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") { + await this.send({ + ...event, + data: { + chunk: _formatOutputChunk(runInfo.runType, chunk), + }, + }, runInfo); + } + yield chunk; + } + } + finally { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + tappedPromiseResolver(); + // Don't delete from the promises map to keep track of which runs have been tapped. + } + } + else { + // otherwise just pass through + yield firstChunk.value; + for await (const chunk of outputStream) { + yield chunk; + } + } } - async persistRun(_run) { } - async onRunCreate(run) { - const persistedRun = await this._convertToCreate(run, this.exampleId); - await this.client.createRun(persistedRun); + async send(payload, run) { + if (this._includeRun(run)) { + await this.writer.write(payload); + } } - async onRunUpdate(run) { - const runUpdate = { - end_time: run.end_time, - error: run.error, - outputs: run.outputs, - events: run.events, + async sendEndEvent(payload, run) { + const tappedPromise = this.tappedPromises.get(payload.run_id); + if (tappedPromise !== undefined) { + void tappedPromise.then(() => { + void this.send(payload, run); + }); + } + else { + await this.send(payload, run); + } + } + async onLLMStart(run) { + const runName = assignName(run); + const runType = run.inputs.messages !== undefined ? "chat_model" : "llm"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, inputs: run.inputs, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - parent_run_id: run.parent_run_id, - extra: run.extra, - session_name: this.projectName, }; - await this.client.updateRun(run.id, runUpdate); - } - getRun(id) { - return this.runMap.get(id); + this.runInfoMap.set(run.id, runInfo); + const eventName = `on_${runType}_start`; + await this.send({ + event: eventName, + data: { + input: run.inputs, + }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - updateFromRunTree(runTree) { - let rootRun = runTree; - const visited = new Set(); - while (rootRun.parent_run) { - if (visited.has(rootRun.id)) - break; - visited.add(rootRun.id); - if (!rootRun.parent_run) - break; - rootRun = rootRun.parent_run; + async onLLMNewToken(run, token, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + kwargs) { + const runInfo = this.runInfoMap.get(run.id); + let chunk; + let eventName; + if (runInfo === undefined) { + throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); } - visited.clear(); - const queue = [rootRun]; - while (queue.length > 0) { - const current = queue.shift(); - if (!current || visited.has(current.id)) - continue; - visited.add(current.id); - // @ts-expect-error Types of property 'events' are incompatible. - this.runMap.set(current.id, current); - if (current.child_runs) { - queue.push(...current.child_runs); + // Top-level streaming events are covered by tapOutputIterable + if (this.runInfoMap.size === 1) { + return; + } + if (runInfo.runType === "chat_model") { + eventName = "on_chat_model_stream"; + if (kwargs?.chunk === undefined) { + chunk = new ai_AIMessageChunk({ content: token, id: `run-${run.id}` }); + } + else { + chunk = kwargs.chunk.message; } } - this.client = runTree.client ?? this.client; - this.projectName = runTree.project_name ?? this.projectName; - this.exampleId = runTree.reference_example_id ?? this.exampleId; + else if (runInfo.runType === "llm") { + eventName = "on_llm_stream"; + if (kwargs?.chunk === undefined) { + chunk = new GenerationChunk({ text: token }); + } + else { + chunk = kwargs.chunk; + } + } + else { + throw new Error(`Unexpected run type ${runInfo.runType}`); + } + await this.send({ + event: eventName, + data: { + chunk, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } - convertToRunTree(id) { - const runTreeMap = {}; - const runTreeList = []; - for (const [id, run] of this.runMap) { - // by converting the run map to a run tree, we are doing a copy - // thus, any mutation performed on the run tree will not be reflected - // back in the run map - // TODO: Stop using `this.runMap` in favour of LangSmith's `RunTree` - const runTree = new run_trees_RunTree({ - ...run, - child_runs: [], - parent_run: undefined, - // inherited properties - client: this.client, - project_name: this.projectName, - reference_example_id: this.exampleId, - tracingEnabled: true, - }); - runTreeMap[id] = runTree; - runTreeList.push([id, run.dotted_order]); + async onLLMEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + let eventName; + if (runInfo === undefined) { + throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); } - runTreeList.sort((a, b) => { - if (!a[1] || !b[1]) - return 0; - return a[1].localeCompare(b[1]); - }); - for (const [id] of runTreeList) { - const run = this.runMap.get(id); - const runTree = runTreeMap[id]; - if (!run || !runTree) - continue; - if (run.parent_run_id) { - const parentRunTree = runTreeMap[run.parent_run_id]; - if (parentRunTree) { - parentRunTree.child_runs.push(runTree); - runTree.parent_run = parentRunTree; + const generations = run.outputs?.generations; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let output; + if (runInfo.runType === "chat_model") { + for (const generation of generations ?? []) { + if (output !== undefined) { + break; } + output = generation[0]?.message; } + eventName = "on_chat_model_end"; } - return runTreeMap[id]; - } - static getTraceableRunTree() { - try { - return getCurrentRunTree(); + else if (runInfo.runType === "llm") { + output = { + generations: generations?.map((generation) => { + return generation.map((chunk) => { + return { + text: chunk.text, + generationInfo: chunk.generationInfo, + }; + }); + }), + llmOutput: run.outputs?.llmOutput ?? {}, + }; + eventName = "on_llm_end"; } - catch { - return undefined; + else { + throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); } + await this.sendEndEvent({ + event: eventName, + data: { + output, + input: runInfo.inputs, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js -const globals_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); -const setGlobalAsyncLocalStorageInstance = (instance) => { - globalThis[globals_TRACING_ALS_KEY] = instance; -}; -const globals_getGlobalAsyncLocalStorageInstance = () => { - return globalThis[globals_TRACING_ALS_KEY]; -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js -/* eslint-disable @typescript-eslint/no-explicit-any */ - - -let queue; -/** - * Creates a queue using the p-queue library. The queue is configured to - * auto-start and has a concurrency of 1, meaning it will process tasks - * one at a time. - */ -function createQueue() { - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - return new PQueue({ - autoStart: true, - concurrency: 1, - }); -} -function getQueue() { - if (typeof queue === "undefined") { - queue = createQueue(); - } - return queue; -} -/** - * Consume a promise, either adding it to the queue or waiting for it to resolve - * @param promiseFn Promise to consume - * @param wait Whether to wait for the promise to resolve or resolve immediately - */ -async function consumeCallback(promiseFn, wait) { - if (wait === true) { - // Clear config since callbacks are not part of the root run - // Avoid using global singleton due to circuluar dependency issues - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== undefined) { - await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); + async onChainStart(run) { + const runName = assignName(run); + const runType = run.run_type ?? "chain"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: run.run_type, + }; + let eventData = {}; + // Workaround Runnable core code not sending input when transform streaming. + if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { + eventData = {}; + runInfo.inputs = {}; + } + else if (run.inputs.input !== undefined) { + eventData.input = run.inputs.input; + runInfo.inputs = run.inputs.input; } else { - await promiseFn(); + eventData.input = run.inputs; + runInfo.inputs = run.inputs; } + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: `on_${runType}_start`, + data: eventData, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - else { - queue = getQueue(); - void queue.add(async () => { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== undefined) { - await asyncLocalStorageInstance.run(undefined, async () => promiseFn()); - } - else { - await promiseFn(); - } - }); - } -} -/** - * Waits for all promises in the queue to resolve. If the queue is - * undefined, it immediately resolves a promise. - */ -function awaitAllCallbacks() { - return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js - -const callbacks_isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; - } - const envVars = [ - "LANGSMITH_TRACING_V2", - "LANGCHAIN_TRACING_V2", - "LANGSMITH_TRACING", - "LANGCHAIN_TRACING", - ]; - return !!envVars.find((envVar) => env_getEnvironmentVariable(envVar) === "true"); -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js - - -/** - * Set a context variable. Context variables are scoped to any - * child runnables called by the current runnable, or globally if set outside - * of any runnable. - * - * @remarks - * This function is only supported in environments that support AsyncLocalStorage, - * including Node.js, Deno, and Cloudflare Workers. - * - * @example - * ```ts - * import { RunnableLambda } from "@langchain/core/runnables"; - * import { - * getContextVariable, - * setContextVariable - * } from "@langchain/core/context"; - * - * const nested = RunnableLambda.from(() => { - * // "bar" because it was set by a parent - * console.log(getContextVariable("foo")); - * - * // Override to "baz", but only for child runnables - * setContextVariable("foo", "baz"); - * - * // Now "baz", but only for child runnables - * return getContextVariable("foo"); - * }); - * - * const runnable = RunnableLambda.from(async () => { - * // Set a context variable named "foo" - * setContextVariable("foo", "bar"); - * - * const res = await nested.invoke({}); - * - * // Still "bar" since child changes do not affect parents - * console.log(getContextVariable("foo")); - * - * return res; - * }); - * - * // undefined, because context variable has not been set yet - * console.log(getContextVariable("foo")); - * - * // Final return value is "baz" - * const result = await runnable.invoke({}); - * ``` - * - * @param name The name of the context variable. - * @param value The value to set. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContextVariable(name, value) { - // Avoid using global singleton due to circuluar dependency issues - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === undefined) { - throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); + async onChainEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === undefined) { + throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + } + const eventName = `on_${run.run_type}_end`; + const inputs = run.inputs ?? runInfo.inputs ?? {}; + const outputs = run.outputs?.output ?? run.outputs; + const data = { + output: outputs, + input: inputs, + }; + if (inputs.input && Object.keys(inputs).length === 1) { + data.input = inputs.input; + runInfo.inputs = inputs.input; + } + await this.sendEndEvent({ + event: eventName, + data, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata ?? {}, + }, runInfo); } - const runTree = asyncLocalStorageInstance.getStore(); - const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; - contextVars[name] = value; - let newValue = {}; - if (isRunTree(runTree)) { - newValue = new RunTree(runTree); + async onToolStart(run) { + const runName = assignName(run); + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: "tool", + inputs: run.inputs ?? {}, + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_tool_start", + data: { + input: run.inputs ?? {}, + }, + name: runName, + run_id: run.id, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - newValue[_CONTEXT_VARIABLES_KEY] = contextVars; - asyncLocalStorageInstance.enterWith(newValue); -} -/** - * Get the value of a previously set context variable. Context variables - * are scoped to any child runnables called by the current runnable, - * or globally if set outside of any runnable. - * - * @remarks - * This function is only supported in environments that support AsyncLocalStorage, - * including Node.js, Deno, and Cloudflare Workers. - * - * @example - * ```ts - * import { RunnableLambda } from "@langchain/core/runnables"; - * import { - * getContextVariable, - * setContextVariable - * } from "@langchain/core/context"; - * - * const nested = RunnableLambda.from(() => { - * // "bar" because it was set by a parent - * console.log(getContextVariable("foo")); - * - * // Override to "baz", but only for child runnables - * setContextVariable("foo", "baz"); - * - * // Now "baz", but only for child runnables - * return getContextVariable("foo"); - * }); - * - * const runnable = RunnableLambda.from(async () => { - * // Set a context variable named "foo" - * setContextVariable("foo", "bar"); - * - * const res = await nested.invoke({}); - * - * // Still "bar" since child changes do not affect parents - * console.log(getContextVariable("foo")); - * - * return res; - * }); - * - * // undefined, because context variable has not been set yet - * console.log(getContextVariable("foo")); - * - * // Final return value is "baz" - * const result = await runnable.invoke({}); - * ``` - * - * @param name The name of the context variable. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getContextVariable(name) { - // Avoid using global singleton due to circuluar dependency issues - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === undefined) { - return undefined; + async onToolEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === undefined) { + throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + } + if (runInfo.inputs === undefined) { + throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + } + const output = run.outputs?.output === undefined ? run.outputs : run.outputs.output; + await this.sendEndEvent({ + event: "on_tool_end", + data: { + output, + input: runInfo.inputs, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); } - const runTree = asyncLocalStorageInstance.getStore(); - return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; -} -const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); -const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; -/** - * Register a callback configure hook to automatically add callback handlers to all runs. - * - * There are two ways to use this: - * - * 1. Using a context variable: - * - Set `contextVar` to specify the variable name - * - Use `setContextVariable()` to store your handler instance - * - * 2. Using an environment variable: - * - Set both `envVar` and `handlerClass` - * - The handler will be instantiated when the env var is set to "true". - * - * @example - * ```typescript - * // Method 1: Using context variable - * import { - * registerConfigureHook, - * setContextVariable - * } from "@langchain/core/context"; - * - * const tracer = new MyCallbackHandler(); - * registerConfigureHook({ - * contextVar: "my_tracer", - * }); - * setContextVariable("my_tracer", tracer); - * - * // ...run code here - * - * // Method 2: Using environment variable - * registerConfigureHook({ - * handlerClass: MyCallbackHandler, - * envVar: "MY_TRACER_ENABLED", - * }); - * process.env.MY_TRACER_ENABLED = "true"; - * - * // ...run code here - * ``` - * - * @param config Configuration object for the hook - * @param config.contextVar Name of the context variable containing the handler instance - * @param config.inheritable Whether child runs should inherit this handler - * @param config.handlerClass Optional callback handler class (required if using envVar) - * @param config.envVar Optional environment variable name to control handler activation - */ -const registerConfigureHook = (config) => { - if (config.envVar && !config.handlerClass) { - throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); + async onRetrieverStart(run) { + const runName = assignName(run); + const runType = "retriever"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: { + query: run.inputs.query, + }, + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_retriever_start", + data: { + input: { + query: run.inputs.query, + }, + }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {}, + }, runInfo); } - setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js - - - - - - - + async onRetrieverEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === undefined) { + throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); + } + await this.sendEndEvent({ + event: "on_retriever_end", + data: { + output: run.outputs?.documents ?? run.outputs, + input: runInfo.inputs, + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + }, runInfo); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleCustomEvent(eventName, data, runId) { + const runInfo = this.runInfoMap.get(runId); + if (runInfo === undefined) { + throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + } + await this.send({ + event: "on_custom_event", + run_id: runId, + name: eventName, + tags: runInfo.tags, + metadata: runInfo.metadata, + data, + }, runInfo); + } + async finish() { + const pendingPromises = [...this.tappedPromises.values()]; + void Promise.all(pendingPromises).finally(() => { + void this.writer.close(); + }); + } +} +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js -function parseCallbackConfigArg(arg) { - if (!arg) { - return {}; +const async_caller_STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409, // Conflict +]; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const defaultFailedAttemptHandler = (error) => { + if (error.message.startsWith("Cancel") || + error.message.startsWith("AbortError") || + error.name === "AbortError") { + throw error; } - else if (Array.isArray(arg) || "name" in arg) { - return { callbacks: arg }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { + throw error; } - else { - return arg; + const status = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error?.response?.status ?? error?.status; + if (status && async_caller_STATUS_NO_RETRY.includes(+status)) { + throw error; } -} -/** - * Manage callbacks from different components of LangChain. - */ -class BaseCallbackManager { - setHandler(handler) { - return this.setHandlers([handler]); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.error?.code === "insufficient_quota") { + const err = new Error(error?.message); + err.name = "InsufficientQuotaError"; + throw err; } -} +}; /** - * Base class for run manager in LangChain. + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. */ -class BaseRunManager { - constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { - Object.defineProperty(this, "runId", { - enumerable: true, - configurable: true, - writable: true, - value: runId - }); - Object.defineProperty(this, "handlers", { +class async_caller_AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { enumerable: true, configurable: true, writable: true, - value: handlers + value: void 0 }); - Object.defineProperty(this, "inheritableHandlers", { + Object.defineProperty(this, "maxRetries", { enumerable: true, configurable: true, writable: true, - value: inheritableHandlers + value: void 0 }); - Object.defineProperty(this, "tags", { + Object.defineProperty(this, "onFailedAttempt", { enumerable: true, configurable: true, writable: true, - value: tags + value: void 0 }); - Object.defineProperty(this, "inheritableTags", { + Object.defineProperty(this, "queue", { enumerable: true, configurable: true, writable: true, - value: inheritableTags + value: void 0 }); - Object.defineProperty(this, "metadata", { + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = + params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } + }), { + onFailedAttempt: this.onFailedAttempt, + retries: this.maxRetries, + randomize: true, + // If needed we can change some of the defaults here, + // but they're quite sensible. + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js + +class RootListenersTracer extends BaseTracer { + constructor({ config, onStart, onEnd, onError, }) { + super({ _awaitHandler: true }); + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: metadata + value: "RootListenersTracer" }); - Object.defineProperty(this, "inheritableMetadata", { + /** The Run's ID. Type UUID */ + Object.defineProperty(this, "rootId", { enumerable: true, configurable: true, writable: true, - value: inheritableMetadata + value: void 0 }); - Object.defineProperty(this, "_parentRunId", { + Object.defineProperty(this, "config", { enumerable: true, configurable: true, - writable: true, - value: _parentRunId - }); - } - get parentRunId() { - return this._parentRunId; - } - async handleText(text) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers))); - } - async handleCustomEvent(eventName, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, _runId, _tags, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers))); - } -} -/** - * Manages callbacks for retriever runs. - */ -class CallbackManagerForRetrieverRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleRetrieverEnd(documents) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleRetrieverError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) { - try { - await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); - } - catch (error) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } -} -class CallbackManagerForLLMRun extends BaseRunManager { - async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) { - try { - await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } -} -class CallbackManagerForChainRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) { - try { - await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleAgentAction(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - async handleAgentEnd(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } -} -class CallbackManagerForToolRun extends BaseRunManager { - getChild(tag) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) { - manager.addTags([tag], false); - } - return manager; - } - async handleToolError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleToolEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) { - try { - await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); - } -} -/** - * @example - * ```typescript - * const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); - * - * // Example of using LLMChain with OpenAI and a simple prompt - * const chain = new LLMChain({ - * llm: new ChatOpenAI({ temperature: 0.9 }), - * prompt, - * }); - * - * // Running the chain with a single question - * const result = await chain.call({ - * question: "What is the airspeed velocity of an unladen swallow?", - * }); - * console.log("The answer is:", result); - * ``` - */ -class CallbackManager extends BaseCallbackManager { - constructor(parentRunId, options) { - super(); - Object.defineProperty(this, "handlers", { + writable: true, + value: void 0 + }); + Object.defineProperty(this, "argOnStart", { enumerable: true, configurable: true, writable: true, - value: [] + value: void 0 }); - Object.defineProperty(this, "inheritableHandlers", { + Object.defineProperty(this, "argOnEnd", { enumerable: true, configurable: true, writable: true, - value: [] + value: void 0 }); - Object.defineProperty(this, "tags", { + Object.defineProperty(this, "argOnError", { enumerable: true, configurable: true, writable: true, - value: [] + value: void 0 }); - Object.defineProperty(this, "inheritableTags", { + this.config = config; + this.argOnStart = onStart; + this.argOnEnd = onEnd; + this.argOnError = onError; + } + /** + * This is a legacy method only called once for an entire run tree + * therefore not useful here + * @param {Run} _ Not used + */ + persistRun(_) { + return Promise.resolve(); + } + async onRunCreate(run) { + if (this.rootId) { + return; + } + this.rootId = run.id; + if (this.argOnStart) { + await this.argOnStart(run, this.config); + } + } + async onRunUpdate(run) { + if (run.id !== this.rootId) { + return; + } + if (!run.error) { + if (this.argOnEnd) { + await this.argOnEnd(run, this.config); + } + } + else if (this.argOnError) { + await this.argOnError(run, this.config); + } + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; +} +/** + * Utility to filter the root event in the streamEvents implementation. + * This is simply binding the arguments to the namespace to make save on + * a bit of typing in the streamEvents implementation. + * + * TODO: Refactor and remove. + */ +class _RootEventFilter { + constructor(fields) { + Object.defineProperty(this, "includeNames", { enumerable: true, configurable: true, writable: true, - value: [] + value: void 0 }); - Object.defineProperty(this, "metadata", { + Object.defineProperty(this, "includeTypes", { enumerable: true, configurable: true, writable: true, - value: {} + value: void 0 }); - Object.defineProperty(this, "inheritableMetadata", { + Object.defineProperty(this, "includeTags", { enumerable: true, configurable: true, writable: true, - value: {} + value: void 0 }); - Object.defineProperty(this, "name", { + Object.defineProperty(this, "excludeNames", { enumerable: true, configurable: true, writable: true, - value: "callback_manager" + value: void 0 }); - Object.defineProperty(this, "_parentRunId", { + Object.defineProperty(this, "excludeTypes", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.handlers = options?.handlers ?? this.handlers; - this.inheritableHandlers = - options?.inheritableHandlers ?? this.inheritableHandlers; - this.tags = options?.tags ?? this.tags; - this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; - this.metadata = options?.metadata ?? this.metadata; - this.inheritableMetadata = - options?.inheritableMetadata ?? this.inheritableMetadata; - this._parentRunId = parentRunId; - } - /** - * Gets the parent run ID, if any. - * - * @returns The parent run ID. - */ - getParentRunId() { - return this._parentRunId; - } - async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - return Promise.all(prompts.map(async (prompt, idx) => { - // Can't have duplicate runs with the same run ID (if provided) - const runId_ = idx === 0 && runId ? runId : v4(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - return Promise.all(messages.map(async (messageGroup, idx) => { - // Can't have duplicate runs with the same run ID (if provided) - const runId_ = idx === 0 && runId ? runId : v4(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - if (handler.handleChatModelStart) { - await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - else if (handler.handleLLMStart) { - const messageString = getBufferString(messageGroup); - await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChainStart(chain, inputs, runId = v4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreChain) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); - } - return consumeCallback(async () => { - try { - await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleToolStart(tool, input, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreAgent) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreRetriever) { - return; - } - if (isBaseTracer(handler)) { - // Create and add run to the run map. - // We do this synchronously to avoid race conditions - // when callbacks are backgrounded. - handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } - return consumeCallback(async () => { - try { - await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); - if (handler.raiseError) { - throw err; - } - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleCustomEvent(eventName, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data, runId, _tags, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreCustomEvent) { - try { - await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); - } - catch (err) { - const logFunction = handler.raiseError - ? console.error - : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) { - throw err; - } - } - } - }, handler.awaitHandlers))); + Object.defineProperty(this, "excludeTags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.includeNames = fields.includeNames; + this.includeTypes = fields.includeTypes; + this.includeTags = fields.includeTags; + this.excludeNames = fields.excludeNames; + this.excludeTypes = fields.excludeTypes; + this.excludeTags = fields.excludeTags; } - addHandler(handler, inherit = true) { - this.handlers.push(handler); - if (inherit) { - this.inheritableHandlers.push(handler); + includeEvent(event, rootType) { + let include = this.includeNames === undefined && + this.includeTypes === undefined && + this.includeTags === undefined; + const eventTags = event.tags ?? []; + if (this.includeNames !== undefined) { + include = include || this.includeNames.includes(event.name); } - } - removeHandler(handler) { - this.handlers = this.handlers.filter((_handler) => _handler !== handler); - this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); - } - setHandlers(handlers, inherit = true) { - this.handlers = []; - this.inheritableHandlers = []; - for (const handler of handlers) { - this.addHandler(handler, inherit); + if (this.includeTypes !== undefined) { + include = include || this.includeTypes.includes(rootType); } - } - addTags(tags, inherit = true) { - this.removeTags(tags); // Remove duplicates - this.tags.push(...tags); - if (inherit) { - this.inheritableTags.push(...tags); + if (this.includeTags !== undefined) { + include = + include || eventTags.some((tag) => this.includeTags?.includes(tag)); } - } - removeTags(tags) { - this.tags = this.tags.filter((tag) => !tags.includes(tag)); - this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); - } - addMetadata(metadata, inherit = true) { - this.metadata = { ...this.metadata, ...metadata }; - if (inherit) { - this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + if (this.excludeNames !== undefined) { + include = include && !this.excludeNames.includes(event.name); } - } - removeMetadata(metadata) { - for (const key of Object.keys(metadata)) { - delete this.metadata[key]; - delete this.inheritableMetadata[key]; + if (this.excludeTypes !== undefined) { + include = include && !this.excludeTypes.includes(rootType); } - } - copy(additionalHandlers = [], inherit = true) { - const manager = new CallbackManager(this._parentRunId); - for (const handler of this.handlers) { - const inheritable = this.inheritableHandlers.includes(handler); - manager.addHandler(handler, inheritable); + if (this.excludeTags !== undefined) { + include = + include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); } - for (const tag of this.tags) { - const inheritable = this.inheritableTags.includes(tag); - manager.addTags([tag], inheritable); + return include; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js +function _escapeNodeLabel(nodeLabel) { + // Escapes the node label for Mermaid syntax. + return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +} +const MARKDOWN_SPECIAL_CHARS = ["*", "_", "`"]; +function _generateMermaidGraphStyles(nodeColors) { + let styles = ""; + for (const [className, color] of Object.entries(nodeColors)) { + styles += `\tclassDef ${className} ${color};\n`; + } + return styles; +} +/** + * Draws a Mermaid graph using the provided graph data + */ +function drawMermaid(nodes, edges, config) { + const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9, } = config ?? {}; + // Initialize Mermaid graph configuration + let mermaidGraph = withStyles + ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` + : "graph TD;\n"; + if (withStyles) { + // Node formatting templates + const defaultClassLabel = "default"; + const formatDict = { + [defaultClassLabel]: "{0}({1})", + }; + if (firstNode !== undefined) { + formatDict[firstNode] = "{0}([{1}]):::first"; } - for (const key of Object.keys(this.metadata)) { - const inheritable = Object.keys(this.inheritableMetadata).includes(key); - manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + if (lastNode !== undefined) { + formatDict[lastNode] = "{0}([{1}]):::last"; } - for (const handler of additionalHandlers) { - if ( - // Prevent multiple copies of console_callback_handler - manager.handlers - .filter((h) => h.name === "console_callback_handler") - .some((h) => h.name === handler.name)) { - continue; + // Add nodes to the graph + for (const [key, node] of Object.entries(nodes)) { + const nodeName = node.name.split(":").pop() ?? ""; + const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) + ? `

${nodeName}

` + : nodeName; + let finalLabel = label; + if (Object.keys(node.metadata ?? {}).length) { + finalLabel += `
${Object.entries(node.metadata ?? {}) + .map(([k, v]) => `${k} = ${v}`) + .join("\n")}`; } - manager.addHandler(handler, inherit); + const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]) + .replace("{0}", _escapeNodeLabel(key)) + .replace("{1}", finalLabel); + mermaidGraph += `\t${nodeLabel}\n`; } - return manager; } - static fromHandlers(handlers) { - class Handler extends BaseCallbackHandler { - constructor() { - super(); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: v4() - }); - Object.assign(this, handlers); - } + // Group edges by their common prefixes + const edgeGroups = {}; + for (const edge of edges) { + const srcParts = edge.source.split(":"); + const tgtParts = edge.target.split(":"); + const commonPrefix = srcParts + .filter((src, i) => src === tgtParts[i]) + .join(":"); + if (!edgeGroups[commonPrefix]) { + edgeGroups[commonPrefix] = []; } - const manager = new this(); - manager.addHandler(new Handler()); - return manager; - } - static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); + edgeGroups[commonPrefix].push(edge); } - // TODO: Deprecate async method in favor of this one. - static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - let callbackManager; - if (inheritableHandlers || localHandlers) { - if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { - callbackManager = new CallbackManager(); - callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); - } - else { - callbackManager = inheritableHandlers; - } - callbackManager = callbackManager.copy(Array.isArray(localHandlers) - ? localHandlers.map(ensureHandler) - : localHandlers?.handlers, false); - } - const verboseEnabled = env_getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || - options?.verbose; - const tracingV2Enabled = tracer_langchain_LangChainTracer.getTraceableRunTree()?.tracingEnabled || - callbacks_isTracingEnabled(); - const tracingEnabled = tracingV2Enabled || - (env_getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); - if (verboseEnabled || tracingEnabled) { - if (!callbackManager) { - callbackManager = new CallbackManager(); - } - if (verboseEnabled && - !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { - const consoleHandler = new ConsoleCallbackHandler(); - callbackManager.addHandler(consoleHandler, true); - } - if (tracingEnabled && - !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { - if (tracingV2Enabled) { - const tracerV2 = new tracer_langchain_LangChainTracer(); - callbackManager.addHandler(tracerV2, true); - // handoff between langchain and langsmith/traceable - // override the parent run ID - callbackManager._parentRunId = - tracer_langchain_LangChainTracer.getTraceableRunTree()?.id ?? - callbackManager._parentRunId; - } - } - } - for (const { contextVar, inheritable = true, handlerClass, envVar, } of _getConfigureHooks()) { - const createIfNotInContext = envVar && env_getEnvironmentVariable(envVar) === "true" && handlerClass; - let handler; - const contextVarValue = contextVar !== undefined ? getContextVariable(contextVar) : undefined; - if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { - handler = contextVarValue; - } - else if (createIfNotInContext) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - handler = new handlerClass({}); - } - if (handler !== undefined) { - if (!callbackManager) { - callbackManager = new CallbackManager(); - } - if (!callbackManager.handlers.some((h) => h.name === handler.name)) { - callbackManager.addHandler(handler, inheritable); - } + const seenSubgraphs = new Set(); + function addSubgraph(edges, prefix) { + const selfLoop = edges.length === 1 && edges[0].source === edges[0].target; + if (prefix && !selfLoop) { + const subgraph = prefix.split(":").pop(); + if (seenSubgraphs.has(subgraph)) { + throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that ` + + "you're reusing a subgraph node with the same name. " + + "Please adjust your graph to have subgraph nodes with unique names."); } + seenSubgraphs.add(subgraph); + mermaidGraph += `\tsubgraph ${subgraph}\n`; } - if (inheritableTags || localTags) { - if (callbackManager) { - callbackManager.addTags(inheritableTags ?? []); - callbackManager.addTags(localTags ?? [], false); + for (const edge of edges) { + const { source, target, data, conditional } = edge; + let edgeLabel = ""; + if (data !== undefined) { + let edgeData = data; + const words = edgeData.split(" "); + if (words.length > wrapLabelNWords) { + edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words + .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords) + .join(" ")).join(" 
 "); + } + edgeLabel = conditional + ? ` -.  ${edgeData}  .-> ` + : ` --  ${edgeData}  --> `; } + else { + edgeLabel = conditional ? " -.-> " : " --> "; + } + mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; } - if (inheritableMetadata || localMetadata) { - if (callbackManager) { - callbackManager.addMetadata(inheritableMetadata ?? {}); - callbackManager.addMetadata(localMetadata ?? {}, false); + // Recursively add nested subgraphs + for (const nestedPrefix in edgeGroups) { + if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) { + addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); } } - return callbackManager; + if (prefix && !selfLoop) { + mermaidGraph += "\tend\n"; + } } -} -function ensureHandler(handler) { - if ("name" in handler) { - return handler; + // Start with the top-level edges (no common prefix) + addSubgraph(edgeGroups[""] ?? [], ""); + // Add remaining subgraphs + for (const prefix in edgeGroups) { + if (!prefix.includes(":") && prefix !== "") { + addSubgraph(edgeGroups[prefix], prefix); + } } - return BaseCallbackHandler.fromMethods(handler); + // Add custom styles for nodes + if (withStyles) { + mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); + } + return mermaidGraph; } /** - * @deprecated Use [`traceable`](https://docs.smith.langchain.com/observability/how_to_guides/tracing/annotate_code) - * from "langsmith" instead. + * Renders Mermaid graph using the Mermaid.INK API. */ -class TraceGroup { - constructor(groupName, options) { - Object.defineProperty(this, "groupName", { - enumerable: true, - configurable: true, - writable: true, - value: groupName - }); - Object.defineProperty(this, "options", { - enumerable: true, - configurable: true, - writable: true, - value: options - }); - Object.defineProperty(this, "runManager", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - async getTraceGroupCallbackManager(group_name, inputs, options) { - const cb = new LangChainTracer(options); - const cm = await CallbackManager.configure([cb]); - const runManager = await cm?.handleChainStart({ - lc: 1, - type: "not_implemented", - id: ["langchain", "callbacks", "groups", group_name], - }, inputs ?? {}); - if (!runManager) { - throw new Error("Failed to create run group callback manager."); +async function drawMermaidPng(mermaidSyntax, config) { + let { backgroundColor = "white" } = config ?? {}; + // Use btoa for compatibility, assume ASCII + const mermaidSyntaxEncoded = btoa(mermaidSyntax); + // Check if the background color is a hexadecimal color code using regex + if (backgroundColor !== undefined) { + const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; + if (!hexColorPattern.test(backgroundColor)) { + backgroundColor = `!${backgroundColor}`; } - return runManager; } - async start(inputs) { - if (!this.runManager) { - this.runManager = await this.getTraceGroupCallbackManager(this.groupName, inputs, this.options); - } - return this.runManager.getChild(); + const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}`; + const res = await fetch(imageUrl); + if (!res.ok) { + throw new Error([ + `Failed to render the graph using the Mermaid.INK API.`, + `Status code: ${res.status}`, + `Status text: ${res.statusText}`, + ].join("\n")); } - async error(err) { - if (this.runManager) { - await this.runManager.handleChainError(err); - this.runManager = undefined; + const content = await res.blob(); + return content; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/core.js +function $constructor(name, initializer, params) { + function init(inst, def) { + var _a; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false, + }); + (_a = inst._zod).traits ?? (_a.traits = new Set()); + inst._zod.traits.add(name); + initializer(inst, def); + // support prototype modifications + for (const k in _.prototype) { + if (!(k in inst)) + Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); } + inst._zod.constr = _; + inst._zod.def = def; } - async end(output) { - if (this.runManager) { - await this.runManager.handleChainEnd(output ?? {}); - this.runManager = undefined; + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = Symbol("zod_brand"); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +const globalConfig = {}; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/util.js +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { } +function util_assertNever(_x) { + throw new Error(); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function util_floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +function defineLazy(object, key, getter) { + const set = false; + Object.defineProperty(object, key, { + get() { + if (!set) { + const value = getter(); + object[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; } + return str; } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function manager_coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" - ? value - : { [defaultKey]: value }; +function esc(str) { + return JSON.stringify(str); } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -async function traceAsGroup(groupOptions, enclosedCode, ...args) { - const traceGroup = new TraceGroup(groupOptions.name, groupOptions); - const callbackManager = await traceGroup.start({ ...args }); +const captureStackTrace = Error.captureStackTrace + ? Error.captureStackTrace + : (..._args) => { }; +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } try { - const result = await enclosedCode(callbackManager, ...args); - await traceGroup.end(manager_coerceToDict(result, "output")); - return result; + const F = Function; + new F(""); + return true; } - catch (err) { - await traceGroup.error(err); - throw err; + catch (_) { + return false; } +}); +function _isObject(o) { + return Object.prototype.toString.call(o) === "[object Object]"; } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js -/* eslint-disable @typescript-eslint/no-explicit-any */ - - - -class async_local_storage_MockAsyncLocalStorage { - getStore() { - return undefined; - } - run(_store, callback) { - return callback(); +function core_util_isPlainObject(o) { + if (isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + // modified prototype + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; } - enterWith(_store) { - return undefined; + return true; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } } + return keyCount; } -const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); -const LC_CHILD_KEY = Symbol.for("lc:child_config"); -class async_local_storage_AsyncLocalStorageProvider { - getInstance() { - return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; +const util_getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); } - getRunnableConfig() { - const storage = this.getInstance(); - // this has the runnable config - // which means that we should also have an instance of a LangChainTracer - // with the run map prepopulated - return storage.getStore()?.extra?.[LC_CHILD_KEY]; +}; +const propertyKeyTypes = new Set(["string", "number", "symbol"]); +const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function util_clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +const NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}; +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const newShape = {}; + const currDef = schema._zod.def; //.shape; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + // pick key + newShape[key] = currDef.shape[key]; } - runWithConfig(config, callback, avoidCreatingRootRunTree) { - const callbackManager = CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); - const storage = this.getInstance(); - const previousValue = storage.getStore(); - const parentRunId = callbackManager?.getParentRunId(); - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); - let runTree; - if (langChainTracer && parentRunId) { - runTree = langChainTracer.convertToRunTree(parentRunId); + return util_clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [], + }); +} +function omit(schema, mask) { + const newShape = { ...schema._zod.def.shape }; + const currDef = schema._zod.def; //.shape; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); } - else if (!avoidCreatingRootRunTree) { - runTree = new run_trees_RunTree({ - name: "", - tracingEnabled: false, - }); + if (!mask[key]) + continue; + delete newShape[key]; + } + return util_clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [], + }); +} +function extend(schema, shape) { + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + checks: [], // delete existing checks + }; + return util_clone(schema, def); +} +function util_merge(a, b) { + return util_clone(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + catchall: b._zod.def.catchall, + checks: [], // delete existing checks + }); +} +function partial(Class, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; } - if (runTree) { - runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config }; + } + else { + for (const key in oldShape) { + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; } - if (previousValue !== undefined && - previousValue[globals_CONTEXT_VARIABLES_KEY] !== undefined) { - if (runTree === undefined) { - runTree = {}; + } + return util_clone(schema, { + ...schema._zod.def, + shape, + checks: [], + }); +} +function required(Class, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); } - runTree[globals_CONTEXT_VARIABLES_KEY] = - previousValue[globals_CONTEXT_VARIABLES_KEY]; + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); } - return storage.run(runTree, callback); } - initializeGlobalInstance(instance) { - if (globals_getGlobalAsyncLocalStorageInstance() === undefined) { - setGlobalAsyncLocalStorageInstance(instance); + else { + for (const key in oldShape) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); } } + return util_clone(schema, { + ...schema._zod.def, + shape, + // optional: [], + checks: [], + }); +} +function aborted(x, startIndex = 0) { + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i].continue !== true) + return true; + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config) { + const full = { ...iss, path: iss.path ?? [] }; + // for backwards compatibility + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"; + full.message = message; + } + // delete (full as any).def; + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// instanceof +class util_Class { + constructor(..._args) { } } -const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/errors.js -const DEFAULT_RECURSION_LIMIT = 25; -async function getCallbackManagerForConfig(config) { - return CallbackManager._configureSync(config?.callbacks, undefined, config?.tags, undefined, config?.metadata); +const initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false, + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false, + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer, 2); + }, + enumerable: true, + // configurable: false, + }); +}; +const $ZodError = $constructor("$ZodError", initializer); +const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; } -function mergeConfigs(...configs) { - // We do not want to call ensureConfig on the empty state here as this may cause - // double loading of callbacks if async local storage is being used. - const copy = {}; - for (const options of configs.filter((c) => !!c)) { - for (const key of Object.keys(options)) { - if (key === "metadata") { - copy[key] = { ...copy[key], ...options[key] }; - } - else if (key === "tags") { - const baseKeys = copy[key] ?? []; - copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; +function formatError(error, _mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues })); } - else if (key === "configurable") { - copy[key] = { ...copy[key], ...options[key] }; + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }); } - else if (key === "timeout") { - if (copy.timeout === undefined) { - copy.timeout = options.timeout; - } - else if (options.timeout !== undefined) { - copy.timeout = Math.min(copy.timeout, options.timeout); - } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }); } - else if (key === "signal") { - if (copy.signal === undefined) { - copy.signal = options.signal; - } - else if (options.signal !== undefined) { - if ("any" in AbortSignal) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - copy.signal = AbortSignal.any([ - copy.signal, - options.signal, - ]); - } - else { - copy.signal = options.signal; - } - } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); } - else if (key === "callbacks") { - const baseCallbacks = copy.callbacks; - const providedCallbacks = options.callbacks; - // callbacks can be either undefined, Array or manager - // so merging two callbacks values has 6 cases - if (Array.isArray(providedCallbacks)) { - if (!baseCallbacks) { - copy.callbacks = providedCallbacks; - } - else if (Array.isArray(baseCallbacks)) { - copy.callbacks = baseCallbacks.concat(providedCallbacks); - } - else { - // baseCallbacks is a manager - const manager = baseCallbacks.copy(); - for (const callback of providedCallbacks) { - manager.addHandler(ensureHandler(callback), true); - } - copy.callbacks = manager; - } - } - else if (providedCallbacks) { - // providedCallbacks is a manager - if (!baseCallbacks) { - copy.callbacks = providedCallbacks; - } - else if (Array.isArray(baseCallbacks)) { - const manager = providedCallbacks.copy(); - for (const callback of baseCallbacks) { - manager.addHandler(ensureHandler(callback), true); - } - copy.callbacks = manager; + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; } else { - // baseCallbacks is also a manager - copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { - handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), - inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), - tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), - inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), - metadata: { - ...baseCallbacks.metadata, - ...providedCallbacks.metadata, - }, - }); + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); } + curr = curr[el]; + i++; } - } - else { - const typedKey = key; - copy[typedKey] = options[typedKey] ?? copy[typedKey]; - } - } - } - return copy; -} -const PRIMITIVES = new Set(["string", "number", "boolean"]); -/** - * Ensure that a passed config is an object with all required keys present. - */ -function ensureConfig(config) { - const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - let empty = { - tags: [], - metadata: {}, - recursionLimit: 25, - runId: undefined, - }; - if (implicitConfig) { - // Don't allow runId and runName to be loaded implicitly, as this can cause - // child runs to improperly inherit their parents' run ids. - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { runId, runName, ...rest } = implicitConfig; - empty = Object.entries(rest).reduce( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (currentConfig, [key, value]) => { - if (value !== undefined) { - // eslint-disable-next-line no-param-reassign - currentConfig[key] = value; - } - return currentConfig; - }, empty); - } - if (config) { - empty = Object.entries(config).reduce( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (currentConfig, [key, value]) => { - if (value !== undefined) { - // eslint-disable-next-line no-param-reassign - currentConfig[key] = value; - } - return currentConfig; - }, empty); - } - if (empty?.configurable) { - for (const key of Object.keys(empty.configurable)) { - if (PRIMITIVES.has(typeof empty.configurable[key]) && - !empty.metadata?.[key]) { - if (!empty.metadata) { - empty.metadata = {}; - } - empty.metadata[key] = empty.configurable[key]; - } - } - } - if (empty.timeout !== undefined) { - if (empty.timeout <= 0) { - throw new Error("Timeout must be a positive number"); + } } - const timeoutSignal = AbortSignal.timeout(empty.timeout); - if (empty.signal !== undefined) { - if ("any" in AbortSignal) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, _mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a, _b; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, issue.path)); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, issue.path); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, issue.path); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } } } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(path) { + const segs = []; + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); else { - empty.signal = timeoutSignal; + if (segs.length) + segs.push("."); + segs.push(seg); } - delete empty.timeout; } - return empty; + return segs.join(""); } -/** - * Helper function that patches runnable configs with updated properties. - */ -function patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId, } = {}) { - const newConfig = ensureConfig(config); - if (callbacks !== undefined) { - /** - * If we're replacing callbacks we need to unset runName - * since that should apply only to the same run as the original callbacks - */ - delete newConfig.runName; - newConfig.callbacks = callbacks; - } - if (recursionLimit !== undefined) { - newConfig.recursionLimit = recursionLimit; +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => a.path.length - b.path.length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); } - if (maxConcurrency !== undefined) { - newConfig.maxConcurrency = maxConcurrency; + // Convert Map to formatted string + return lines.join("\n"); +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/parse.js + + + +const _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); } - if (runName !== undefined) { - newConfig.runName = runName; + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; } - if (configurable !== undefined) { - newConfig.configurable = { ...newConfig.configurable, ...configurable }; + return result.value; +}; +const parse_parse = /* @__PURE__*/ _parse($ZodRealError); +const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; } - if (runId !== undefined) { - delete newConfig.runId; + return result.value; +}; +const parse_parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); } - return newConfig; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function pickRunnableConfigKeys(config) { - return config + return result.issues.length ? { - configurable: config.configurable, - recursionLimit: config.recursionLimit, - callbacks: config.callbacks, - tags: config.tags, - metadata: config.metadata, - maxConcurrency: config.maxConcurrency, - timeout: config.timeout, - signal: config.signal, + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), } - : undefined; + : { success: true, data: result.value }; +}; +const parse_safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + } + : { success: true, data: result.value }; +}; +const parse_safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/regexes.js +const cuid = /^[cC][^\s-]{8,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const regexes_uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emoji = (/* unused pure expression or super */ null && (`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`)); +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = +// /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/; +const hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) +const e164 = /^\+(?:[0-9]){6,14}[0-9]$/; +// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js -async function raceWithSignal(promise, signal) { - if (signal === undefined) { - return promise; - } - let listener; - return Promise.race([ - promise.catch((err) => { - if (!signal?.aborted) { - throw err; - } - else { - return undefined; - } - }), - new Promise((_, reject) => { - listener = () => { - reject(new Error("Aborted")); - }; - signal.addEventListener("abort", listener); - // Must be here inside the promise to avoid a race condition - if (signal.aborted) { - reject(new Error("Aborted")); - } - }), - ]).finally(() => signal.removeEventListener("abort", listener)); +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const time = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex = `${time}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); } +const string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^\d+n?$/; +const integer = /^\d+$/; +const number = /^-?\d+(?:\.\d+)?/i; +const regexes_boolean = /true|false/i; +const _null = /null/i; -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js +const _undefined = /undefined/i; +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/checks.js +// import { $ZodType } from "./schemas.js"; -/* - * Support async iterator syntax for ReadableStreams in all environments. - * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -class IterableReadableStream extends ReadableStream { - constructor() { - super(...arguments); - Object.defineProperty(this, "reader", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - } - ensureReader() { - if (!this.reader) { - this.reader = this.getReader(); - } - } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) { - this.reader.releaseLock(); // release lock when stream becomes closed - return { - done: true, - value: undefined, - }; - } - else { - return { - done: false, - value: result.value, - }; - } + + +const $ZodCheck = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}))); +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; } - catch (e) { - this.reader.releaseLock(); // release lock when stream becomes errored - throw e; + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; } - } - async return() { - this.ensureReader(); - // If wrapped in a Node stream, cancel is already called. - if (this.locked) { - const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet - this.reader.releaseLock(); // release lock first - await cancelPromise; // now await it + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckGreaterThan = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; } - return { done: true, value: undefined }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async throw(e) { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); // cancel first, but don't await yet - this.reader.releaseLock(); // release lock first - await cancelPromise; // now await it + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; } - throw e; - } - [Symbol.asyncIterator]() { - return this; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore Not present in Node 18 types, required in latest Node 22 - async [Symbol.asyncDispose]() { - await this.return(); - } - static fromReadableStream(stream) { - // From https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams#reading_the_stream - const reader = stream.getReader(); - return new IterableReadableStream({ - start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - // When no more data needs to be consumed, close the stream - if (done) { - controller.close(); - return; - } - // Enqueue the next data chunk into our target stream - controller.enqueue(value); - return pump(); - }); - } - }, - cancel() { - reader.releaseLock(); - }, + payload.issues.push({ + origin: origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, }); - } - static fromAsyncGenerator(generator) { - return new IterableReadableStream({ - async pull(controller) { - const { value, done } = await generator.next(); - // When no more data needs to be consumed, close the stream - if (done) { - controller.close(); - } - // Fix: `else if (value)` will hang the streaming when nullish value (e.g. empty string) is pulled - controller.enqueue(value); - }, - async cancel(reason) { - await generator.return(reason); - }, + }; +}))); +const $ZodCheckMultipleOf = +/*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? payload.value % def.value === BigInt(0) + : util.floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, }); - } -} -function atee(iter, length = 2) { - const buffers = Array.from({ length }, () => []); - return buffers.map(async function* makeIter(buffer) { - while (true) { - if (buffer.length === 0) { - const result = await iter.next(); - for (const buffer of buffers) { - buffer.push(result); + }; +}))); +const $ZodCheckNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = regexes.integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); } - } - else if (buffer[0].done) { return; } - else { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield buffer.shift().value; - } } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst, + }); + } + }; +}))); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; }); -} -function concat(first, second) { - if (Array.isArray(first) && Array.isArray(second)) { - return first.concat(second); - } - else if (typeof first === "string" && typeof second === "string") { - return (first + second); - } - else if (typeof first === "number" && typeof second === "number") { - return (first + second); - } - else if ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - "concat" in first && - // eslint-disable-next-line @typescript-eslint/no-explicit-any - typeof first.concat === "function") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return first.concat(second); - } - else if (typeof first === "object" && typeof second === "object") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const chunk = { ...first }; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - for (const [key, value] of Object.entries(second)) { - if (key in chunk && !Array.isArray(chunk[key])) { - chunk[key] = concat(chunk[key], value); - } - else { - chunk[key] = value; - } + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); } - return chunk; - } - else { - throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); - } -} -class AsyncGeneratorWithSetup { - constructor(params) { - Object.defineProperty(this, "generator", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inst, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + input, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "setup", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + input, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; + }; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + input: payload.value, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "signal", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxLength", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.length !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = util.getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "firstResult", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + }; +}))); +const $ZodCheckMinLength = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinLength", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.length !== undefined; + }; + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = util.getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "firstResultUsed", { - enumerable: true, - configurable: true, - writable: true, - value: false + }; +}))); +const $ZodCheckLengthEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLengthEquals", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.when = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.length !== undefined; + }; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = util.getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + input: payload.value, + inst, + continue: !def.abort, }); - this.generator = params.generator; - this.config = params.config; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.signal = params.signal ?? this.config?.signal; - // setup is a promise that resolves only after the first iterator value - // is available. this is useful when setup of several piped generators - // needs to happen in logical order, ie. in the order in which input to - // to each generator is available. - this.setup = new Promise((resolve, reject) => { - void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(params.config), async () => { - this.firstResult = params.generator.next(); - if (params.startSetup) { - this.firstResult.then(params.startSetup).then(resolve, reject); - } - else { - this.firstResult.then((_result) => resolve(undefined), reject); - } - }, true); + }; +}))); +const $ZodCheckStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckStringFormat", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + (_a = inst._zod).check ?? (_a.check = (payload) => { + if (!def.pattern) + throw new Error("Not implemented."); + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, }); - } - async next(...args) { - this.signal?.throwIfAborted(); - if (!this.firstResultUsed) { - this.firstResultUsed = true; - return this.firstResult; + }); +}))); +const $ZodCheckRegex = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckLowerCase = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = regexes.lowercase); + $ZodCheckStringFormat.init(inst, def); +}))); +const $ZodCheckUpperCase = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = regexes.uppercase); + $ZodCheckStringFormat.init(inst, def); +}))); +const $ZodCheckIncludes = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = util.escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckStartsWith = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckEndsWith = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); } - return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(this.config), this.signal - ? async () => { - return raceWithSignal(this.generator.next(...args), this.signal); - } - : async () => { - return this.generator.next(...args); - }, true); - } - async return(value) { - return this.generator.return(value); - } - async throw(e) { - return this.generator.throw(e); - } - [Symbol.asyncIterator]() { - return this; - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore Not present in Node 18 types, required in latest Node 22 - async [Symbol.asyncDispose]() { - await this.return(); - } -} -async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { - const gen = new AsyncGeneratorWithSetup({ - generator, - startSetup, - signal, + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; }); - const setup = await gen.setup; - return { output: to(gen, setup, ...args), setup }; -} + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}))); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/versions.js +const versions_version = { + major: 4, + minor: 0, + patch: 0, +}; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/schemas.js -/** - * List of jsonpatch JSONPatchOperations, which describe how to create the run state - * from an empty dict. This is the minimal representation of the log, designed to - * be serialized as JSON and sent over the wire to reconstruct the log on the other - * side. Reconstruction of the state can be done with any jsonpatch-compliant library, - * see https://jsonpatch.com for more information. - */ -class RunLogPatch { - constructor(fields) { - Object.defineProperty(this, "ops", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.ops = fields.ops ?? []; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = core_applyPatch({}, ops); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunLog({ - ops, - state: states[states.length - 1].newDocument, - }); - } -} -class RunLog extends RunLogPatch { - constructor(fields) { - super(fields); - Object.defineProperty(this, "state", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.state = fields.state; + + + + +const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + // avoids issues with using Math.random() in Next.js caching + util.defineLazy(inst._zod, "id", () => def.type + "_" + util.randomString(10)); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = version; + const checks = [...(inst._zod.def.checks ?? [])]; + // if inst is itself a checks.$ZodCheck, run it as a check + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = core_applyPatch(this.state, other.ops); - return new RunLog({ ops, state: states[states.length - 1].newDocument }); + // + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } } - static fromRunLogPatch(patch) { - const states = core_applyPatch({}, patch.ops); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunLog({ - ops: patch.ops, - state: states[states.length - 1].newDocument, + if (checks.length === 0) { + // deferred initializer + // inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; }); } -} -const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; -/** - * Extract standardized inputs from a run. - * - * Standardizes the inputs based on the type of the runnable used. - * - * @param run - Run object - * @param schemaFormat - The schema format to use. - * - * @returns Valid inputs are only dict. By conventions, inputs always represented - * invocation using named arguments. - * A null means that the input is not yet known! - */ -async function _getStandardizedInputs(run, schemaFormat) { - if (schemaFormat === "original") { - throw new Error("Do not assign inputs with original schema drop the key for now. " + - "When inputs are added to streamLog they should be added with " + - "standardized schema for streaming events."); + else { + const runChecks = (payload, checks, ctx) => { + let isAborted = util.aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.when) { + const shouldRun = ch._zod.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new core.$ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = util.aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = util.aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new core.$ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; } - const { inputs } = run; - if (["retriever", "llm", "prompt"].includes(run.run_type)) { - return inputs; + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } + catch (_) { + return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); + } + }, + vendor: "zod", + version: 1, + }; +}))); + +const $ZodString = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + checks.$ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}))); +const $ZodGUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.guid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodUUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = regexes.uuid(v)); + } + else + def.pattern ?? (def.pattern = regexes.uuid()); + $ZodStringFormat.init(inst, def); +}))); +const $ZodEmail = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = regexes.email); + $ZodStringFormat.init(inst, def); +}))); +const $ZodURL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const url = new URL(payload.value); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: regexes.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + } + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodEmoji = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = regexes.emoji()); + $ZodStringFormat.init(inst, def); +}))); +const $ZodNanoID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.nanoid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cuid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCUID2 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cuid2); + $ZodStringFormat.init(inst, def); +}))); +const $ZodULID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ulid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodXID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.xid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodKSUID = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ksuid); + $ZodStringFormat.init(inst, def); +}))); +const $ZodISODateTime = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes.datetime(def)); + $ZodStringFormat.init(inst, def); + const _super = inst._zod.check; +}))); +const $ZodISODate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes.date); + $ZodStringFormat.init(inst, def); +}))); +const $ZodISOTime = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes.time(def)); + $ZodStringFormat.init(inst, def); + const _super = inst._zod.check; +}))); +const $ZodISODuration = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = regexes.duration); + $ZodStringFormat.init(inst, def); +}))); +const $ZodIPv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = `ipv4`; + }); +}))); +const $ZodIPv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes.ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = `ipv6`; + }); + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + // return; + } + catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cidrv4); + $ZodStringFormat.init(inst, def); +}))); +const $ZodCIDRv6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } + catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}))); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; } - if (Object.keys(inputs).length === 1 && inputs?.input === "") { - return undefined; + catch { + return false; } - // new style chains - // These nest an additional 'input' key inside the 'inputs' to make sure - // the input is always a dict. We need to unpack and user the inner value. - // We should try to fix this in Runnables and callbacks/tracers - // Runnables should be using a null type here not a placeholder - // dict. - return inputs.input; } -async function _getStandardizedOutputs(run, schemaFormat) { - const { outputs } = run; - if (schemaFormat === "original") { - // Return the old schema, without standardizing anything - return outputs; - } - if (["retriever", "llm", "prompt"].includes(run.run_type)) { - return outputs; +const $ZodBase64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes.base64); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + inst._zod.bag.contentEncoding = "base64"; + }); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes.base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes.base64url); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst) => { + inst._zod.bag.contentEncoding = "base64url"; + }); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodE164 = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = regexes.e164); + $ZodStringFormat.init(inst, def); +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function schemas_isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; } - // TODO: Remove this hacky check - if (outputs !== undefined && - Object.keys(outputs).length === 1 && - outputs?.output !== undefined) { - return outputs.output; + catch { + return false; } - return outputs; -} -function isChatGenerationChunk(x) { - return x !== undefined && x.message !== undefined; } -/** - * Class that extends the `BaseTracer` class from the - * `langchain.callbacks.tracers.base` module. It represents a callback - * handler that logs the execution of runs and emits `RunLog` instances to a - * `RunLogStream`. - */ -class LogStreamCallbackHandler extends BaseTracer { - constructor(fields) { - super({ _awaitHandler: true, ...fields }); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_schemaFormat", { - enumerable: true, - configurable: true, - writable: true, - value: "original" +const $ZodJWT = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (schemas_isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, }); - Object.defineProperty(this, "rootId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + }; +}))); +const $ZodNumber = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? "Infinity" + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), }); - Object.defineProperty(this, "keyMapByRunId", { - enumerable: true, - configurable: true, - writable: true, - value: {} + return payload; + }; +}))); +const $ZodNumberFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNumber", (inst, def) => { + checks.$ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checksp +}))); +const $ZodBoolean = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "counterMapByRunName", { - enumerable: true, - configurable: true, - writable: true, - value: {} + return payload; + }; +}))); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + const { value: input } = payload; + if (typeof input === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "log_stream_tracer" + return payload; + }; +}))); +const $ZodAny = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}))); +const schemas_$ZodUnknown = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}))); +const $ZodNever = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const { value: input } = payload; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, }); - Object.defineProperty(this, "lc_prefer_streaming", { - enumerable: true, - configurable: true, - writable: true, - value: true + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}))); +function handleObjectResult(result, final, key) { + // if(isOptional) + if (result.issues.length) { + final.issues.push(...util.prefixIssues(key, result.issues)); + } + final.value[key] = result.value; +} +function handleOptionalObjectResult(result, final, key, input) { + if (result.issues.length) { + // validation failed against value schema + if (input[key] === undefined) { + // if input was undefined, ignore the error + if (key in input) { + final.value[key] = undefined; + } + else { + final.value[key] = result.value; + } + } + else { + final.issues.push(...util.prefixIssues(key, result.issues)); + } } - [Symbol.asyncIterator]() { - return this.receiveStream; + else if (result.value === undefined) { + // validation returned `undefined` + if (key in input) + final.value[key] = undefined; } - async persistRun(_run) { - // This is a legacy method only called once for an entire run tree - // and is therefore not useful here + else { + // non-undefined value + final.value[key] = result.value; } - _includeRun(run) { - if (run.id === this.rootId) { - return false; +} +const $ZodObject = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + const _normalized = util.cached(() => { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!(def.shape[k] instanceof $ZodType)) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } } - const runTags = run.tags ?? []; - let include = this.includeNames === undefined && - this.includeTags === undefined && - this.includeTypes === undefined; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(run.name); + const okeys = util.optionalKeys(def.shape); + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; + }); + util.defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const { keys, optionalKeys } = _normalized.value; + const parseStr = (key) => { + const k = util.esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + for (const key of keys) { + ids[key] = util.randomString(15); + } + // A: preserve key order { + doc.write(`const newResult = {}`); + for (const key of keys) { + if (optionalKeys.has(key)) { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + const k = util.esc(key); + doc.write(` + if (${id}.issues.length) { + if (input[${k}] === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}], + })) + ); + } + } else if (${id}.value === undefined) { + if (${k} in input) newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(run.run_type); + `); + } + else { + const id = ids[key]; + // const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${util.esc(key)}, ...iss.path] : [${util.esc(key)}] + })));`); + doc.write(`newResult[${util.esc(key)}] = ${id}.value`); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject = util.isObject; + const jit = !core.globalConfig.jitless; + const allowsEval = util.allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const { catchall } = def; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; } - if (this.includeTags !== undefined) { - include = - include || - runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + const proms = []; + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(run.name); + else { + payload.value = {}; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + // do not add omitted optional keys + // if (!(key in input)) { + // if (optionalKeys.has(key)) continue; + // payload.issues.push({ + // code: "invalid_type", + // path: [key], + // expected: "nonoptional", + // note: `Missing required key: "${key}"`, + // input, + // inst, + // }); + // } + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + if (r instanceof Promise) { + proms.push(r.then((r) => isOptional ? handleOptionalObjectResult(r, payload, key, input) : handleObjectResult(r, payload, key))); + } + else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); + } + else { + handleObjectResult(r, payload, key); + } + } } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(run.run_type); + if (!catchall) { + // return payload; + return proms.length ? Promise.all(proms).then(() => payload) : payload; } - if (this.excludeTags !== undefined) { - include = - include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + const unrecognized = []; + // iterate over input keys + const keySet = value.keySet; + const _catchall = catchall._zod; + const t = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handleObjectResult(r, payload, key))); + } + else { + handleObjectResult(r, payload, key); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; +}))); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; } - return include; } - async *tapOutputIterable(runId, output) { - // Tap an output async iterator to stream its values to the log. - for await (const chunk of output) { - // root run is handled in .streamLog() - if (runId !== this.rootId) { - // if we can't find the run silently ignore - // eg. because this run wasn't included in the log - const key = this.keyMapByRunId[runId]; - if (key) { - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${key}/streamed_output/-`, - value: chunk, - }, - ], - })); + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + util.defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + inst._zod.parse = (payload, ctx) => { + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}))); +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +(/* unused pure expression or super */ null && (core.$constructor("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + util.defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = util.cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); } + map.set(v, o); } - yield chunk; } - } - async onRunCreate(run) { - if (this.rootId === undefined) { - this.rootId = run.id; - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "replace", - path: "", - value: { - id: run.id, - name: run.name, - type: run.run_type, - streamed_output: [], - final_output: undefined, - logs: {}, - }, - }, - ], - })); + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util.isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; } - if (!this._includeRun(run)) { - return; + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); } - if (this.counterMapByRunName[run.name] === undefined) { - this.counterMapByRunName[run.name] = 0; + if (def.unionFallback) { + return _super(payload, ctx); } - this.counterMapByRunName[run.name] += 1; - const count = this.counterMapByRunName[run.name]; - this.keyMapByRunId[run.id] = - count === 1 ? run.name : `${run.name}:${count}`; - const logEntry = { - id: run.id, - name: run.name, - type: run.run_type, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - start_time: new Date(run.start_time).toISOString(), - streamed_output: [], - streamed_output_str: [], - final_output: undefined, - end_time: undefined, - }; - if (this._schemaFormat === "streaming_events") { - logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}))); +const $ZodIntersection = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const { value: input } = payload; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); } - await this.writer.write(new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${this.keyMapByRunId[run.id]}`, - value: logEntry, - }, - ], - })); + return handleIntersectionResults(payload, left, right); + }; +}))); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; } - async onRunUpdate(run) { - try { - const runName = this.keyMapByRunId[run.id]; - if (runName === undefined) { - return; + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (util.isPlainObject(a) && util.isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; } - const ops = []; - if (this._schemaFormat === "streaming_events") { - ops.push({ - op: "replace", - path: `/logs/${runName}/inputs`, - value: await _getStandardizedInputs(run, this._schemaFormat), + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (util.aborted(result)) + return result; + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const schemas_$ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = []; + const proms = []; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + input, + inst, + origin: "array", + ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), }); + return payload; } - ops.push({ - op: "add", - path: `/logs/${runName}/final_output`, - value: await _getStandardizedOutputs(run, this._schemaFormat), + } + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) + if (i >= optStart) + continue; + const result = item._zod.run({ + value: input[i], + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ + value: el, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodRecord = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util.isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, }); - if (run.end_time !== undefined) { - ops.push({ - op: "add", - path: `/logs/${runName}/end_time`, - value: new Date(run.end_time).toISOString(), + return payload; + } + const proms = []; + if (def.keyType._zod.values) { + const values = def.keyType._zod.values; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, }); } - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); } - finally { - if (run.id === this.rootId) { - const patch = new RunLogPatch({ - ops: [ - { - op: "replace", - path: "/final_output", - value: await _getStandardizedOutputs(run, this._schemaFormat), - }, - ], - }); - await this.writer.write(patch); - if (this.autoClose) { - await this.writer.close(); + else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + input: key, + path: [key], + inst, + }); + payload.value[keyResult.value] = keyResult.value; + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; } } } - } - async onLLMNewToken(run, token, kwargs) { - const runName = this.keyMapByRunId[run.id]; - if (runName === undefined) { - return; + if (proms.length) { + return Promise.all(proms).then(() => payload); } - // TODO: Remove hack - const isChatModel = run.inputs.messages !== undefined; - let streamedOutputValue; - if (isChatModel) { - if (isChatGenerationChunk(kwargs?.chunk)) { - streamedOutputValue = kwargs?.chunk; + return payload; + }; +}))); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); } else { - streamedOutputValue = new ai_AIMessageChunk({ - id: `run-${run.id}`, - content: token, - }); + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); } } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } else { - streamedOutputValue = token; + final.issues.push({ + origin: "map", + code: "invalid_key", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); } - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: `/logs/${runName}/streamed_output_str/-`, - value: token, - }, - { - op: "add", - path: `/logs/${runName}/streamed_output/-`, - value: streamedOutputValue, - }, - ], - }); - await this.writer.write(patch); } + final.value.set(keyResult.value, valueResult.value); } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js -const RUN_KEY = "__run"; -/** - * Chunk of a single generation. Used for streaming. - */ -class GenerationChunk { - constructor(fields) { - Object.defineProperty(this, "text", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = util.getEnumValues(def.entries); + inst._zod.values = new Set(values); + inst._zod.pattern = new RegExp(`^(${values + .filter((k) => util.propertyKeyTypes.has(typeof k)) + .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o.toString())) + .join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "generationInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + return payload; + }; +}))); +const $ZodLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp(`^(${def.values + .map((o) => (typeof o === "string" ? util.escapeRegex(o) : o ? o.toString() : String(o))) + .join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, }); - this.text = fields.text; - this.generationInfo = fields.generationInfo; - } - concat(chunk) { - return new GenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo, - }, + return payload; + }; +}))); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new core.$ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}))); +const schemas_$ZodOptional = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + util.defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; + }); + util.defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; +}))); +const $ZodNullable = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + util.defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined; + }); + util.defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}))); +const $ZodDefault = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault always returns the default value immediately. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}))); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}))); +const $ZodNonOptional = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}))); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +const $ZodCatch = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + util.defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }, + input: payload.value, + }); + payload.issues = []; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }, + input: payload.value, + }); + payload.issues = []; + } + return payload; + }; +}))); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "values", () => def.in._zod.values); + util.defineLazy(inst._zod, "optin", () => def.in._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.out._zod.optout); + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def, ctx)); + } + return handlePipeResult(left, def, ctx); + }; +}))); +function handlePipeResult(left, def, ctx) { + if (util.aborted(left)) { + return left; } + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); } -class ChatGenerationChunk extends GenerationChunk { - constructor(fields) { - super(fields); - Object.defineProperty(this, "message", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.message = fields.message; +const $ZodReadonly = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + util.defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}))); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (part instanceof $ZodType) { + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } } - concat(chunk) { - return new ChatGenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo, - }, - message: this.message.concat(chunk.message), - }); + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "template_literal", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazy(inst._zod, "innerType", () => def.getter()); + util.defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); + util.defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); + util.defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin); + util.defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}))); +const $ZodCustom = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustom", (inst, def) => { + checks.$ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}))); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util.issue(_iss)); } } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ar.js + +const error = () => { + const Sizable = { + string: { unit: "حرف", verb: "أن يحوي" }, + file: { unit: "بايت", verb: "أن يحوي" }, + array: { unit: "عنصر", verb: "أن يحوي" }, + set: { unit: "عنصر", verb: "أن يحوي" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "مدخل", + email: "بريد إلكتروني", + url: "رابط", + emoji: "إيموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاريخ ووقت بمعيار ISO", + date: "تاريخ بمعيار ISO", + time: "وقت بمعيار ISO", + duration: "مدة بمعيار ISO", + ipv4: "عنوان IPv4", + ipv6: "عنوان IPv6", + cidrv4: "مدى عناوين بصيغة IPv4", + cidrv6: "مدى عناوين بصيغة IPv6", + base64: "نَص بترميز base64-encoded", + base64url: "نَص بترميز base64url-encoded", + json_string: "نَص على هيئة JSON", + e164: "رقم هاتف بمعيار E.164", + jwt: "JWT", + template_literal: "مدخل", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `مدخلات غير مقبولة: يفترض إدخال ${issue.expected}، ولكن تم إدخال ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `مدخلات غير مقبولة: يفترض إدخال ${util.stringifyPrimitive(issue.values[0])}`; + return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "عنصر"}`; + return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `نَص غير مقبول: يجب أن يبدأ بـ "${issue.prefix}"`; + if (_issue.format === "ends_with") + return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; + if (_issue.format === "regex") + return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} غير مقبول`; + } + case "not_multiple_of": + return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`; + case "unrecognized_keys": + return `معرف${issue.keys.length > 1 ? "ات" : ""} غريب${issue.keys.length > 1 ? "ة" : ""}: ${util.joinValues(issue.keys, "، ")}`; + case "invalid_key": + return `معرف غير مقبول في ${issue.origin}`; + case "invalid_union": + return "مدخل غير مقبول"; + case "invalid_element": + return `مدخل غير مقبول في ${issue.origin}`; + default: + return "مدخل غير مقبول"; + } + }; +}; +/* harmony default export */ function ar() { + return { + localeError: error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/az.js +const az_error = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "element", verb: "olmalıdır" }, + set: { unit: "element", verb: "olmalıdır" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Yanlış dəyər: gözlənilən ${issue.expected}, daxil olan ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Yanlış dəyər: gözlənilən ${util.stringifyPrimitive(issue.values[0])}`; + return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; + if (_issue.format === "ends_with") + return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; + if (_issue.format === "includes") + return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; + if (_issue.format === "regex") + return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; + return `Yanlış ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Yanlış ədəd: ${issue.divisor} ilə bölünə bilən olmalıdır`; + case "unrecognized_keys": + return `Tanınmayan açar${issue.keys.length > 1 ? "lar" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} daxilində yanlış açar`; + case "invalid_union": + return "Yanlış dəyər"; + case "invalid_element": + return `${issue.origin} daxilində yanlış dəyər`; + default: + return `Yanlış dəyər`; + } + }; +}; +/* harmony default export */ function az() { + return { + localeError: az_error(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/be.js -function assignName({ name, serialized, }) { - if (name !== undefined) { - return name; +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; } - if (serialized?.name !== undefined) { - return serialized.name; + if (lastDigit === 1) { + return one; } - else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) { - return serialized.id[serialized.id.length - 1]; + if (lastDigit >= 2 && lastDigit <= 4) { + return few; } - return "Unnamed"; + return many; } -const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; -/** - * Class that extends the `BaseTracer` class from the - * `langchain.callbacks.tracers.base` module. It represents a callback - * handler that logs the execution of runs and emits `RunLog` instances to a - * `RunLogStream`. - */ -class EventStreamCallbackHandler extends BaseTracer { - constructor(fields) { - super({ _awaitHandler: true, ...fields }); - Object.defineProperty(this, "autoClose", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "runInfoMap", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - Object.defineProperty(this, "tappedPromises", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - Object.defineProperty(this, "transformStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "writer", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "receiveStream", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "event_stream_tracer" - }); - Object.defineProperty(this, "lc_prefer_streaming", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); +const be_error = () => { + const Sizable = { + string: { + unit: { + one: "сімвал", + few: "сімвалы", + many: "сімвалаў", + }, + verb: "мець", + }, + array: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў", + }, + verb: "мець", + }, + set: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў", + }, + verb: "мець", + }, + file: { + unit: { + one: "байт", + few: "байты", + many: "байтаў", + }, + verb: "мець", + }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - [Symbol.asyncIterator]() { - return this.receiveStream; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "лік"; + } + case "object": { + if (Array.isArray(data)) { + return "масіў"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "увод", + email: "email адрас", + url: "URL", + emoji: "эмодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата і час", + date: "ISO дата", + time: "ISO час", + duration: "ISO працягласць", + ipv4: "IPv4 адрас", + ipv6: "IPv6 адрас", + cidrv4: "IPv4 дыяпазон", + cidrv6: "IPv6 дыяпазон", + base64: "радок у фармаце base64", + base64url: "радок у фармаце base64url", + json_string: "JSON радок", + e164: "нумар E.164", + jwt: "JWT", + template_literal: "увод", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Няправільны ўвод: чакаўся ${issue.expected}, атрымана ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Няправільны ўвод: чакалася ${util.stringifyPrimitive(issue.values[0])}`; + return `Няправільны варыянт: чакаўся адзін з ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + const maxValue = Number(issue.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`; + } + return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + const minValue = Number(issue.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`; + } + return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; + if (_issue.format === "regex") + return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; + return `Няправільны ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Няправільны лік: павінен быць кратным ${issue.divisor}`; + case "unrecognized_keys": + return `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Няправільны ключ у ${issue.origin}`; + case "invalid_union": + return "Няправільны ўвод"; + case "invalid_element": + return `Няправільнае значэнне ў ${issue.origin}`; + default: + return `Няправільны ўвод`; + } + }; +}; +/* harmony default export */ function be() { + return { + localeError: be_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ca.js + +const ca_error = () => { + const Sizable = { + string: { unit: "caràcters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async persistRun(_run) { - // This is a legacy method only called once for an entire run tree - // and is therefore not useful here + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrada", + email: "adreça electrònica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adreça IPv4", + ipv6: "adreça IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${parsedType(issue.input)}`; + // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Valor invàlid: s'esperava ${util.stringifyPrimitive(issue.values[0])}`; + return `Opció invàlida: s'esperava una de ${util.joinValues(issue.values, " o ")}`; + case "too_big": { + const adj = issue.inclusive ? "com a màxim" : "menys de"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} fos ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "com a mínim" : "més de"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Format invàlid: ha de començar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format invàlid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; + return `Format invàlid per a ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Número invàlid: ha de ser múltiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clau${issue.keys.length > 1 ? "s" : ""} no reconeguda${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clau invàlida a ${issue.origin}`; + case "invalid_union": + return "Entrada invàlida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element invàlid a ${issue.origin}`; + default: + return `Entrada invàlida`; + } + }; +}; +/* harmony default export */ function ca() { + return { + localeError: ca_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/cs.js + +const cs_error = () => { + const Sizable = { + string: { unit: "znaků", verb: "mít" }, + file: { unit: "bajtů", verb: "mít" }, + array: { unit: "prvků", verb: "mít" }, + set: { unit: "prvků", verb: "mít" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - _includeRun(run) { - const runTags = run.tags ?? []; - let include = this.includeNames === undefined && - this.includeTags === undefined && - this.includeTypes === undefined; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(run.name); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "číslo"; + } + case "string": { + return "řetězec"; + } + case "boolean": { + return "boolean"; + } + case "bigint": { + return "bigint"; + } + case "function": { + return "funkce"; + } + case "symbol": { + return "symbol"; + } + case "undefined": { + return "undefined"; + } + case "object": { + if (Array.isArray(data)) { + return "pole"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(run.runType); + return t; + }; + const Nouns = { + regex: "regulární výraz", + email: "e-mailová adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a čas ve formátu ISO", + date: "datum ve formátu ISO", + time: "čas ve formátu ISO", + duration: "doba trvání ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "řetězec zakódovaný ve formátu base64", + base64url: "řetězec zakódovaný ve formátu base64url", + json_string: "řetězec ve formátu JSON", + e164: "číslo E.164", + jwt: "JWT", + template_literal: "vstup", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Neplatný vstup: očekáváno ${issue.expected}, obdrženo ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Neplatný vstup: očekáváno ${util.stringifyPrimitive(issue.values[0])}`; + return `Neplatná možnost: očekávána jedna z hodnot ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.maximum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.minimum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; + return `Neplatný formát ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Neplatné číslo: musí být násobkem ${issue.divisor}`; + case "unrecognized_keys": + return `Neznámé klíče: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Neplatný klíč v ${issue.origin}`; + case "invalid_union": + return "Neplatný vstup"; + case "invalid_element": + return `Neplatná hodnota v ${issue.origin}`; + default: + return `Neplatný vstup`; } - if (this.includeTags !== undefined) { - include = - include || - runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined; + }; +}; +/* harmony default export */ function cs() { + return { + localeError: cs_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/de.js + +const de_error = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "Zahl"; + } + case "object": { + if (Array.isArray(data)) { + return "Array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(run.name); + return t; + }; + const Nouns = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ungültige Eingabe: erwartet ${issue.expected}, erhalten ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ungültige Eingabe: erwartet ${util.stringifyPrimitive(issue.values[0])}`; + return `Ungültige Option: erwartet eine von ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ungültiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ungültiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ungültig: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ungültiger Schlüssel in ${issue.origin}`; + case "invalid_union": + return "Ungültige Eingabe"; + case "invalid_element": + return `Ungültiger Wert in ${issue.origin}`; + default: + return `Ungültige Eingabe`; } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(run.runType); + }; +}; +/* harmony default export */ function de() { + return { + localeError: de_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/en.js + +const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Invalid input: expected ${issue.expected}, received ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* harmony default export */ function locales_en() { + return { + localeError: en_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/es.js + +const es_error = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; + } + case "object": { + if (Array.isArray(data)) { + return "arreglo"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrada", + email: "dirección de correo electrónico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duración ISO", + ipv4: "dirección IPv4", + ipv6: "dirección IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrada inválida: se esperaba ${issue.expected}, recibido ${parsedType(issue.input)}`; + // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrada inválida: se esperaba ${util.stringifyPrimitive(issue.values[0])}`; + return `Opción inválida: se esperaba una de ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Demasiado grande: se esperaba que ${issue.origin ?? "valor"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${issue.origin ?? "valor"} fuera ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Demasiado pequeño: se esperaba que ${issue.origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado pequeño: se esperaba que ${issue.origin} fuera ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inválida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inválida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; + return `Inválido ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Número inválido: debe ser múltiplo de ${issue.divisor}`; + case "unrecognized_keys": + return `Llave${issue.keys.length > 1 ? "s" : ""} desconocida${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Llave inválida en ${issue.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido en ${issue.origin}`; + default: + return `Entrada inválida`; + } + }; +}; +/* harmony default export */ function es() { + return { + localeError: es_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fa.js + +const fa_error = () => { + const Sizable = { + string: { unit: "کاراکتر", verb: "داشته باشد" }, + file: { unit: "بایت", verb: "داشته باشد" }, + array: { unit: "آیتم", verb: "داشته باشد" }, + set: { unit: "آیتم", verb: "داشته باشد" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "آرایه"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ورودی", + email: "آدرس ایمیل", + url: "URL", + emoji: "ایموجی", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاریخ و زمان ایزو", + date: "تاریخ ایزو", + time: "زمان ایزو", + duration: "مدت زمان ایزو", + ipv4: "IPv4 آدرس", + ipv6: "IPv6 آدرس", + cidrv4: "IPv4 دامنه", + cidrv6: "IPv6 دامنه", + base64: "base64-encoded رشته", + base64url: "base64url-encoded رشته", + json_string: "JSON رشته", + e164: "E.164 عدد", + jwt: "JWT", + template_literal: "ورودی", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ورودی نامعتبر: می‌بایست ${issue.expected} می‌بود، ${parsedType(issue.input)} دریافت شد`; + case "invalid_value": + if (issue.values.length === 1) { + return `ورودی نامعتبر: می‌بایست ${util.stringifyPrimitive(issue.values[0])} می‌بود`; + } + return `گزینه نامعتبر: می‌بایست یکی از ${util.joinValues(issue.values, "|")} می‌بود`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; + } + return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} باشد`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`; + } + return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; + } + if (_issue.format === "ends_with") { + return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; + } + if (_issue.format === "includes") { + return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; + } + if (_issue.format === "regex") { + return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; + } + return `${Nouns[_issue.format] ?? issue.format} نامعتبر`; + } + case "not_multiple_of": + return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`; + case "unrecognized_keys": + return `کلید${issue.keys.length > 1 ? "های" : ""} ناشناس: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `کلید ناشناس در ${issue.origin}`; + case "invalid_union": + return `ورودی نامعتبر`; + case "invalid_element": + return `مقدار نامعتبر در ${issue.origin}`; + default: + return `ورودی نامعتبر`; + } + }; +}; +/* harmony default export */ function fa() { + return { + localeError: fa_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fi.js + +const fi_error = () => { + const Sizable = { + string: { unit: "merkkiä", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "päivämäärän" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.excludeTags !== undefined) { - include = - include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return t; + }; + const Nouns = { + regex: "säännöllinen lauseke", + email: "sähköpostiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-päivämäärä", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Virheellinen tyyppi: odotettiin ${issue.expected}, oli ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Virheellinen syöte: täytyy olla ${util.stringifyPrimitive(issue.values[0])}`; + return `Virheellinen valinta: täytyy olla yksi seuraavista: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen syöte`; } - return include; + }; +}; +/* harmony default export */ function fi() { + return { + localeError: fi_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fr.js + +const fr_error = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async *tapOutputIterable(runId, outputStream) { - const firstChunk = await outputStream.next(); - if (firstChunk.done) { - return; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombre"; + } + case "object": { + if (Array.isArray(data)) { + return "tableau"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - const runInfo = this.runInfoMap.get(runId); - // Run has finished, don't issue any stream events. - // An example of this is for runnables that use the default - // implementation of .stream(), which delegates to .invoke() - // and calls .onChainEnd() before passing it to the iterator. - if (runInfo === undefined) { - yield firstChunk.value; - return; + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrée invalide : ${issue.expected} attendu, ${parsedType(issue.input)} reçu`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrée invalide : ${util.stringifyPrimitive(issue.values[0])} attendu`; + return `Option invalide : une valeur parmi ${util.joinValues(issue.values, "|")} attendue`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; + return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue.origin}`; + default: + return `Entrée invalide`; } - // Match format from handlers below - function _formatOutputChunk(eventType, data) { - if (eventType === "llm" && typeof data === "string") { - return new GenerationChunk({ text: data }); + }; +}; +/* harmony default export */ function fr() { + return { + localeError: fr_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/fr-CA.js + +const fr_CA_error = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - return data; - } - let tappedPromise = this.tappedPromises.get(runId); - // if we are the first to tap, issue stream events - if (tappedPromise === undefined) { - let tappedPromiseResolver; - tappedPromise = new Promise((resolve) => { - tappedPromiseResolver = resolve; - }); - this.tappedPromises.set(runId, tappedPromise); - try { - const event = { - event: `on_${runInfo.runType}_stream`, - run_id: runId, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - data: {}, - }; - await this.send({ - ...event, - data: { - chunk: _formatOutputChunk(runInfo.runType, firstChunk.value), - }, - }, runInfo); - yield firstChunk.value; - for await (const chunk of outputStream) { - // Don't yield tool and retriever stream events - if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") { - await this.send({ - ...event, - data: { - chunk: _formatOutputChunk(runInfo.runType, chunk), - }, - }, runInfo); - } - yield chunk; + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - } - finally { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - tappedPromiseResolver(); - // Don't delete from the promises map to keep track of which runs have been tapped. } } - else { - // otherwise just pass through - yield firstChunk.value; - for await (const chunk of outputStream) { - yield chunk; - } + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrée invalide : attendu ${issue.expected}, reçu ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrée invalide : attendu ${util.stringifyPrimitive(issue.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "≤" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Trop grand : attendu que ${issue.origin ?? "la valeur"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue.origin ?? "la valeur"} soit ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "≥" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue.origin}`; + default: + return `Entrée invalide`; } + }; +}; +/* harmony default export */ function fr_CA() { + return { + localeError: fr_CA_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/he.js + +const he_error = () => { + const Sizable = { + string: { unit: "אותיות", verb: "לכלול" }, + file: { unit: "בייטים", verb: "לכלול" }, + array: { unit: "פריטים", verb: "לכלול" }, + set: { unit: "פריטים", verb: "לכלול" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async send(payload, run) { - if (this._includeRun(run)) { - await this.writer.write(payload); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "קלט", + email: "כתובת אימייל", + url: "כתובת רשת", + emoji: "אימוג'י", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "תאריך וזמן ISO", + date: "תאריך ISO", + time: "זמן ISO", + duration: "משך זמן ISO", + ipv4: "כתובת IPv4", + ipv6: "כתובת IPv6", + cidrv4: "טווח IPv4", + cidrv6: "טווח IPv6", + base64: "מחרוזת בבסיס 64", + base64url: "מחרוזת בבסיס 64 לכתובות רשת", + json_string: "מחרוזת JSON", + e164: "מספר E.164", + jwt: "JWT", + template_literal: "קלט", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `קלט לא תקין: צריך ${issue.expected}, התקבל ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `קלט לא תקין: צריך ${util.stringifyPrimitive(issue.values[0])}`; + return `קלט לא תקין: צריך אחת מהאפשרויות ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `גדול מדי: ${issue.origin ?? "value"} צריך להיות ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `גדול מדי: ${issue.origin ?? "value"} צריך להיות ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `קטן מדי: ${issue.origin} צריך להיות ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `קטן מדי: ${issue.origin} צריך להיות ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `מחרוזת לא תקינה: חייבת להתחיל ב"${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `מחרוזת לא תקינה: חייבת להסתיים ב "${_issue.suffix}"`; + if (_issue.format === "includes") + return `מחרוזת לא תקינה: חייבת לכלול "${_issue.includes}"`; + if (_issue.format === "regex") + return `מחרוזת לא תקינה: חייבת להתאים לתבנית ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} לא תקין`; + } + case "not_multiple_of": + return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`; + case "unrecognized_keys": + return `מפתח${issue.keys.length > 1 ? "ות" : ""} לא מזוה${issue.keys.length > 1 ? "ים" : "ה"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `מפתח לא תקין ב${issue.origin}`; + case "invalid_union": + return "קלט לא תקין"; + case "invalid_element": + return `ערך לא תקין ב${issue.origin}`; + default: + return `קלט לא תקין`; } + }; +}; +/* harmony default export */ function he() { + return { + localeError: he_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/hu.js + +const hu_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async sendEndEvent(payload, run) { - const tappedPromise = this.tappedPromises.get(payload.run_id); - if (tappedPromise !== undefined) { - void tappedPromise.then(() => { - void this.send(payload, run); - }); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "szám"; + } + case "object": { + if (Array.isArray(data)) { + return "tömb"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - else { - await this.send(payload, run); + return t; + }; + const Nouns = { + regex: "bemenet", + email: "email cím", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO időbélyeg", + date: "ISO dátum", + time: "ISO idő", + duration: "ISO időintervallum", + ipv4: "IPv4 cím", + ipv6: "IPv6 cím", + cidrv4: "IPv4 tartomány", + cidrv6: "IPv6 tartomány", + base64: "base64-kódolt string", + base64url: "base64url-kódolt string", + json_string: "JSON string", + e164: "E.164 szám", + jwt: "JWT", + template_literal: "bemenet", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Érvénytelen bemenet: a várt érték ${issue.expected}, a kapott érték ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Érvénytelen bemenet: a várt érték ${util.stringifyPrimitive(issue.values[0])}`; + return `Érvénytelen opció: valamelyik érték várt ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; + if (_issue.format === "ends_with") + return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; + if (_issue.format === "includes") + return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; + if (_issue.format === "regex") + return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; + return `Érvénytelen ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Érvénytelen kulcs ${issue.origin}`; + case "invalid_union": + return "Érvénytelen bemenet"; + case "invalid_element": + return `Érvénytelen érték: ${issue.origin}`; + default: + return `Érvénytelen bemenet`; } + }; +}; +/* harmony default export */ function hu() { + return { + localeError: hu_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/id.js + +const id_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onLLMStart(run) { - const runName = assignName(run); - const runType = run.inputs.messages !== undefined ? "chat_model" : "llm"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: run.inputs, - }; - this.runInfoMap.set(run.id, runInfo); - const eventName = `on_${runType}_start`; - await this.send({ - event: eventName, - data: { - input: run.inputs, - }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {}, - }, runInfo); - } - async onLLMNewToken(run, token, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - kwargs) { - const runInfo = this.runInfoMap.get(run.id); - let chunk; - let eventName; - if (runInfo === undefined) { - throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - // Top-level streaming events are covered by tapOutputIterable - if (this.runInfoMap.size === 1) { - return; + return t; + }; + const Nouns = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input tidak valid: diharapkan ${issue.expected}, diterima ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input tidak valid: diharapkan ${util.stringifyPrimitive(issue.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue.origin ?? "value"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue.origin ?? "value"} menjadi ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue.origin}`; + default: + return `Input tidak valid`; } - if (runInfo.runType === "chat_model") { - eventName = "on_chat_model_stream"; - if (kwargs?.chunk === undefined) { - chunk = new ai_AIMessageChunk({ content: token, id: `run-${run.id}` }); + }; +}; +/* harmony default export */ function id() { + return { + localeError: id_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/it.js + +const it_error = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numero"; } - else { - chunk = kwargs.chunk.message; + case "object": { + if (Array.isArray(data)) { + return "vettore"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - else if (runInfo.runType === "llm") { - eventName = "on_llm_stream"; - if (kwargs?.chunk === undefined) { - chunk = new GenerationChunk({ text: token }); + return t; + }; + const Nouns = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input non valido: atteso ${issue.expected}, ricevuto ${parsedType(issue.input)}`; + // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input non valido: atteso ${util.stringifyPrimitive(issue.values[0])}`; + return `Opzione non valida: atteso uno tra ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue.divisor}`; + case "unrecognized_keys": + return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue.origin}`; + default: + return `Input non valido`; + } + }; +}; +/* harmony default export */ function it() { + return { + localeError: it_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ja.js + +const ja_error = () => { + const Sizable = { + string: { unit: "文字", verb: "である" }, + file: { unit: "バイト", verb: "である" }, + array: { unit: "要素", verb: "である" }, + set: { unit: "要素", verb: "である" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "数値"; } - else { - chunk = kwargs.chunk; + case "object": { + if (Array.isArray(data)) { + return "配列"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - else { - throw new Error(`Unexpected run type ${runInfo.runType}`); + return t; + }; + const Nouns = { + regex: "入力値", + email: "メールアドレス", + url: "URL", + emoji: "絵文字", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日時", + date: "ISO日付", + time: "ISO時刻", + duration: "ISO期間", + ipv4: "IPv4アドレス", + ipv6: "IPv6アドレス", + cidrv4: "IPv4範囲", + cidrv6: "IPv6範囲", + base64: "base64エンコード文字列", + base64url: "base64urlエンコード文字列", + json_string: "JSON文字列", + e164: "E.164番号", + jwt: "JWT", + template_literal: "入力値", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `無効な入力: ${issue.expected}が期待されましたが、${parsedType(issue.input)}が入力されました`; + case "invalid_value": + if (issue.values.length === 1) + return `無効な入力: ${util.stringifyPrimitive(issue.values[0])}が期待されました`; + return `無効な選択: ${util.joinValues(issue.values, "、")}のいずれかである必要があります`; + case "too_big": { + const adj = issue.inclusive ? "以下である" : "より小さい"; + const sizing = getSizing(issue.origin); + if (sizing) + return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; + return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${adj}必要があります`; + } + case "too_small": { + const adj = issue.inclusive ? "以上である" : "より大きい"; + const sizing = getSizing(issue.origin); + if (sizing) + return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${sizing.unit}${adj}必要があります`; + return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${adj}必要があります`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; + if (_issue.format === "ends_with") + return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; + if (_issue.format === "includes") + return `無効な文字列: "${_issue.includes}"を含む必要があります`; + if (_issue.format === "regex") + return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; + return `無効な${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `無効な数値: ${issue.divisor}の倍数である必要があります`; + case "unrecognized_keys": + return `認識されていないキー${issue.keys.length > 1 ? "群" : ""}: ${util.joinValues(issue.keys, "、")}`; + case "invalid_key": + return `${issue.origin}内の無効なキー`; + case "invalid_union": + return "無効な入力"; + case "invalid_element": + return `${issue.origin}内の無効な値`; + default: + return `無効な入力`; } - await this.send({ - event: eventName, - data: { - chunk, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); + }; +}; +/* harmony default export */ function ja() { + return { + localeError: ja_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/kh.js + +const kh_error = () => { + const Sizable = { + string: { unit: "តួអក្សរ", verb: "គួរមាន" }, + file: { unit: "បៃ", verb: "គួរមាន" }, + array: { unit: "ធាតុ", verb: "គួរមាន" }, + set: { unit: "ធាតុ", verb: "គួរមាន" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onLLMEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - let eventName; - if (runInfo === undefined) { - throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); - } - const generations = run.outputs?.generations; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let output; - if (runInfo.runType === "chat_model") { - for (const generation of generations ?? []) { - if (output !== undefined) { - break; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ"; + } + case "object": { + if (Array.isArray(data)) { + return "អារេ (Array)"; + } + if (data === null) { + return "គ្មានតម្លៃ (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - output = generation[0]?.message; } - eventName = "on_chat_model_end"; } - else if (runInfo.runType === "llm") { - output = { - generations: generations?.map((generation) => { - return generation.map((chunk) => { - return { - text: chunk.text, - generationInfo: chunk.generationInfo, - }; - }); - }), - llmOutput: run.outputs?.llmOutput ?? {}, - }; - eventName = "on_llm_end"; - } - else { - throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); + return t; + }; + const Nouns = { + regex: "ទិន្នន័យបញ្ចូល", + email: "អាសយដ្ឋានអ៊ីមែល", + url: "URL", + emoji: "សញ្ញាអារម្មណ៍", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", + date: "កាលបរិច្ឆេទ ISO", + time: "ម៉ោង ISO", + duration: "រយៈពេល ISO", + ipv4: "អាសយដ្ឋាន IPv4", + ipv6: "អាសយដ្ឋាន IPv6", + cidrv4: "ដែនអាសយដ្ឋាន IPv4", + cidrv6: "ដែនអាសយដ្ឋាន IPv6", + base64: "ខ្សែអក្សរអ៊ិកូដ base64", + base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", + json_string: "ខ្សែអក្សរ JSON", + e164: "លេខ E.164", + jwt: "JWT", + template_literal: "ទិន្នន័យបញ្ចូល", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue.expected} ប៉ុន្តែទទួលបាន ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${util.stringifyPrimitive(issue.values[0])}`; + return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; + return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; + if (_issue.format === "regex") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; + return `មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`; + case "unrecognized_keys": + return `រកឃើញសោមិនស្គាល់៖ ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; + case "invalid_union": + return `ទិន្នន័យមិនត្រឹមត្រូវ`; + case "invalid_element": + return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; + default: + return `ទិន្នន័យមិនត្រឹមត្រូវ`; } - await this.sendEndEvent({ - event: eventName, - data: { - output, - input: runInfo.inputs, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); + }; +}; +/* harmony default export */ function kh() { + return { + localeError: kh_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ko.js + +const ko_error = () => { + const Sizable = { + string: { unit: "문자", verb: "to have" }, + file: { unit: "바이트", verb: "to have" }, + array: { unit: "개", verb: "to have" }, + set: { unit: "개", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onChainStart(run) { - const runName = assignName(run); - const runType = run.run_type ?? "chain"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: run.run_type, - }; - let eventData = {}; - // Workaround Runnable core code not sending input when transform streaming. - if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { - eventData = {}; - runInfo.inputs = {}; - } - else if (run.inputs.input !== undefined) { - eventData.input = run.inputs.input; - runInfo.inputs = run.inputs.input; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - else { - eventData.input = run.inputs; - runInfo.inputs = run.inputs; + return t; + }; + const Nouns = { + regex: "입력", + email: "이메일 주소", + url: "URL", + emoji: "이모지", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 날짜시간", + date: "ISO 날짜", + time: "ISO 시간", + duration: "ISO 기간", + ipv4: "IPv4 주소", + ipv6: "IPv6 주소", + cidrv4: "IPv4 범위", + cidrv6: "IPv6 범위", + base64: "base64 인코딩 문자열", + base64url: "base64url 인코딩 문자열", + json_string: "JSON 문자열", + e164: "E.164 번호", + jwt: "JWT", + template_literal: "입력", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `잘못된 입력: 예상 타입은 ${issue.expected}, 받은 타입은 ${parsedType(issue.input)}입니다`; + case "invalid_value": + if (issue.values.length === 1) + return `잘못된 입력: 값은 ${util.stringifyPrimitive(issue.values[0])} 이어야 합니다`; + return `잘못된 옵션: ${util.joinValues(issue.values, "또는 ")} 중 하나여야 합니다`; + case "too_big": { + const adj = issue.inclusive ? "이하" : "미만"; + const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) + return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue.inclusive ? "이상" : "초과"; + const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) { + return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; + } + if (_issue.format === "ends_with") + return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; + if (_issue.format === "includes") + return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; + if (_issue.format === "regex") + return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; + return `잘못된 ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`; + case "unrecognized_keys": + return `인식할 수 없는 키: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `잘못된 키: ${issue.origin}`; + case "invalid_union": + return `잘못된 입력`; + case "invalid_element": + return `잘못된 값: ${issue.origin}`; + default: + return `잘못된 입력`; } - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: `on_${runType}_start`, - data: eventData, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {}, - }, runInfo); + }; +}; +/* harmony default export */ function ko() { + return { + localeError: ko_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/mk.js + +const mk_error = () => { + const Sizable = { + string: { unit: "знаци", verb: "да имаат" }, + file: { unit: "бајти", verb: "да имаат" }, + array: { unit: "ставки", verb: "да имаат" }, + set: { unit: "ставки", verb: "да имаат" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onChainEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === undefined) { - throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "број"; + } + case "object": { + if (Array.isArray(data)) { + return "низа"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - const eventName = `on_${run.run_type}_end`; - const inputs = run.inputs ?? runInfo.inputs ?? {}; - const outputs = run.outputs?.output ?? run.outputs; - const data = { - output: outputs, - input: inputs, - }; - if (inputs.input && Object.keys(inputs).length === 1) { - data.input = inputs.input; - runInfo.inputs = inputs.input; + return t; + }; + const Nouns = { + regex: "внес", + email: "адреса на е-пошта", + url: "URL", + emoji: "емоџи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO датум и време", + date: "ISO датум", + time: "ISO време", + duration: "ISO времетраење", + ipv4: "IPv4 адреса", + ipv6: "IPv6 адреса", + cidrv4: "IPv4 опсег", + cidrv6: "IPv6 опсег", + base64: "base64-енкодирана низа", + base64url: "base64url-енкодирана низа", + json_string: "JSON низа", + e164: "E.164 број", + jwt: "JWT", + template_literal: "внес", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Грешен внес: се очекува ${issue.expected}, примено ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`; + return `Грешана опција: се очекува една ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да има ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементи"}`; + return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да биде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Премногу мал: се очекува ${issue.origin} да има ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Премногу мал: се очекува ${issue.origin} да биде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неважечка низа: мора да вклучува "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Грешен број: мора да биде делив со ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Грешен клуч во ${issue.origin}`; + case "invalid_union": + return "Грешен внес"; + case "invalid_element": + return `Грешна вредност во ${issue.origin}`; + default: + return `Грешен внес`; } - await this.sendEndEvent({ - event: eventName, - data, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata ?? {}, - }, runInfo); - } - async onToolStart(run) { - const runName = assignName(run); - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: "tool", - inputs: run.inputs ?? {}, - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_tool_start", - data: { - input: run.inputs ?? {}, - }, - name: runName, - run_id: run.id, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - }, runInfo); + }; +}; +/* harmony default export */ function mk() { + return { + localeError: mk_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ms.js + +const ms_error = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onToolEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === undefined) { - throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombor"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (runInfo.inputs === undefined) { - throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + return t; + }; + const Nouns = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input tidak sah: dijangka ${issue.expected}, diterima ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input tidak sah: dijangka ${util.stringifyPrimitive(issue.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} adalah ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue.origin}`; + default: + return `Input tidak sah`; } - const output = run.outputs?.output === undefined ? run.outputs : run.outputs.output; - await this.sendEndEvent({ - event: "on_tool_end", - data: { - output, - input: runInfo.inputs, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); + }; +}; +/* harmony default export */ function ms() { + return { + localeError: ms_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/nl.js + +const nl_error = () => { + const Sizable = { + string: { unit: "tekens" }, + file: { unit: "bytes" }, + array: { unit: "elementen" }, + set: { unit: "elementen" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onRetrieverStart(run) { - const runName = assignName(run); - const runType = "retriever"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: { - query: run.inputs.query, - }, - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_retriever_start", - data: { - input: { - query: run.inputs.query, - }, - }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {}, - }, runInfo); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "getal"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ongeldige invoer: verwacht ${issue.expected}, ontving ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ongeldige invoer: verwacht ${util.stringifyPrimitive(issue.values[0])}`; + return `Ongeldige optie: verwacht één van ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Te lang: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; + return `Te lang: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} is`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Te kort: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} bevat`; + } + return `Te kort: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue.origin}`; + default: + return `Ongeldige invoer`; + } + }; +}; +/* harmony default export */ function nl() { + return { + localeError: nl_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/no.js + +const no_error = () => { + const Sizable = { + string: { unit: "tegn", verb: "å ha" }, + file: { unit: "bytes", verb: "å ha" }, + array: { unit: "elementer", verb: "å inneholde" }, + set: { unit: "elementer", verb: "å inneholde" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onRetrieverEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === undefined) { - throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "tall"; + } + case "object": { + if (Array.isArray(data)) { + return "liste"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - await this.sendEndEvent({ - event: "on_retriever_end", - data: { - output: run.outputs?.documents ?? run.outputs, - input: runInfo.inputs, - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - }, runInfo); + return t; + }; + const Nouns = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-område", + ipv6: "IPv6-område", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ugyldig input: forventet ${issue.expected}, fikk ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ugyldig verdi: forventet ${util.stringifyPrimitive(issue.values[0])}`; + return `Ugyldig valg: forventet en av ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ugyldig streng: må starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: må ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: må inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; + return `Ugyldig ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: må være et multiplum av ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ugyldig nøkkel i ${issue.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +/* harmony default export */ function no() { + return { + localeError: no_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ota.js + +const ota_error = () => { + const Sizable = { + string: { unit: "harf", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "unsur", verb: "olmalıdır" }, + set: { unit: "unsur", verb: "olmalıdır" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async handleCustomEvent(eventName, data, runId) { - const runInfo = this.runInfoMap.get(runId); - if (runInfo === undefined) { - throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numara"; + } + case "object": { + if (Array.isArray(data)) { + return "saf"; + } + if (data === null) { + return "gayb"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - await this.send({ - event: "on_custom_event", - run_id: runId, - name: eventName, - tags: runInfo.tags, - metadata: runInfo.metadata, - data, - }, runInfo); + return t; + }; + const Nouns = { + regex: "giren", + email: "epostagâh", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO hengâmı", + date: "ISO tarihi", + time: "ISO zamanı", + duration: "ISO müddeti", + ipv4: "IPv4 nişânı", + ipv6: "IPv6 nişânı", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-şifreli metin", + base64url: "base64url-şifreli metin", + json_string: "JSON metin", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "giren", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Fâsit giren: umulan ${issue.expected}, alınan ${parsedType(issue.input)}`; + // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Fâsit giren: umulan ${util.stringifyPrimitive(issue.values[0])}`; + return `Fâsit tercih: mûteberler ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; + return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; + } + return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; + if (_issue.format === "ends_with") + return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; + if (_issue.format === "regex") + return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; + return `Fâsit ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`; + case "unrecognized_keys": + return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} için tanınmayan anahtar var.`; + case "invalid_union": + return "Giren tanınamadı."; + case "invalid_element": + return `${issue.origin} için tanınmayan kıymet var.`; + default: + return `Kıymet tanınamadı.`; + } + }; +}; +/* harmony default export */ function ota() { + return { + localeError: ota_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ps.js + +const ps_error = () => { + const Sizable = { + string: { unit: "توکي", verb: "ولري" }, + file: { unit: "بایټس", verb: "ولري" }, + array: { unit: "توکي", verb: "ولري" }, + set: { unit: "توکي", verb: "ولري" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async finish() { - const pendingPromises = [...this.tappedPromises.values()]; - void Promise.all(pendingPromises).finally(() => { - void this.writer.close(); - }); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "ارې"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ورودي", + email: "بریښنالیک", + url: "یو آر ال", + emoji: "ایموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "نیټه او وخت", + date: "نېټه", + time: "وخت", + duration: "موده", + ipv4: "د IPv4 پته", + ipv6: "د IPv6 پته", + cidrv4: "د IPv4 ساحه", + cidrv6: "د IPv6 ساحه", + base64: "base64-encoded متن", + base64url: "base64url-encoded متن", + json_string: "JSON متن", + e164: "د E.164 شمېره", + jwt: "JWT", + template_literal: "ورودي", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ناسم ورودي: باید ${issue.expected} وای, مګر ${parsedType(issue.input)} ترلاسه شو`; + case "invalid_value": + if (issue.values.length === 1) { + return `ناسم ورودي: باید ${util.stringifyPrimitive(issue.values[0])} وای`; + } + return `ناسم انتخاب: باید یو له ${util.joinValues(issue.values, "|")} څخه وای`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; + } + return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} وي`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`; + } + return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; + } + if (_issue.format === "ends_with") { + return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; + } + if (_issue.format === "includes") { + return `ناسم متن: باید "${_issue.includes}" ولري`; + } + if (_issue.format === "regex") { + return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; + } + return `${Nouns[_issue.format] ?? issue.format} ناسم دی`; + } + case "not_multiple_of": + return `ناسم عدد: باید د ${issue.divisor} مضرب وي`; + case "unrecognized_keys": + return `ناسم ${issue.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `ناسم کلیډ په ${issue.origin} کې`; + case "invalid_union": + return `ناسمه ورودي`; + case "invalid_element": + return `ناسم عنصر په ${issue.origin} کې`; + default: + return `ناسمه ورودي`; + } + }; +}; +/* harmony default export */ function ps() { + return { + localeError: ps_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/pl.js + +const pl_error = () => { + const Sizable = { + string: { unit: "znaków", verb: "mieć" }, + file: { unit: "bajtów", verb: "mieć" }, + array: { unit: "elementów", verb: "mieć" }, + set: { unit: "elementów", verb: "mieć" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "liczba"; + } + case "object": { + if (Array.isArray(data)) { + return "tablica"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "wyrażenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ciąg znaków zakodowany w formacie base64", + base64url: "ciąg znaków zakodowany w formacie base64url", + json_string: "ciąg znaków w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wejście", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Nieprawidłowe dane wejściowe: oczekiwano ${issue.expected}, otrzymano ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Nieprawidłowe dane wejściowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`; + return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; + return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Nieprawidłowy klucz w ${issue.origin}`; + case "invalid_union": + return "Nieprawidłowe dane wejściowe"; + case "invalid_element": + return `Nieprawidłowa wartość w ${issue.origin}`; + default: + return `Nieprawidłowe dane wejściowe`; + } + }; +}; +/* harmony default export */ function pl() { + return { + localeError: pl_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/pt.js +const pt_error = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "padrão", + email: "endereço de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "duração ISO", + ipv4: "endereço IPv4", + ipv6: "endereço IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Tipo inválido: esperado ${issue.expected}, recebido ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrada inválida: esperado ${util.stringifyPrimitive(issue.values[0])}`; + return `Opção inválida: esperada uma das ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Muito grande: esperado que ${issue.origin ?? "valor"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue.origin ?? "valor"} fosse ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Texto inválido: deve começar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inválido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inválido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} inválido`; + } + case "not_multiple_of": + return `Número inválido: deve ser múltiplo de ${issue.divisor}`; + case "unrecognized_keys": + return `Chave${issue.keys.length > 1 ? "s" : ""} desconhecida${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Chave inválida em ${issue.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido em ${issue.origin}`; + default: + return `Campo inválido`; + } + }; +}; +/* harmony default export */ function pt() { + return { + localeError: pt_error(), + }; +} -const async_caller_STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409, // Conflict -]; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const defaultFailedAttemptHandler = (error) => { - if (error.message.startsWith("Cancel") || - error.message.startsWith("AbortError") || - error.name === "AbortError") { - throw error; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ru.js + +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; + if (lastDigit === 1) { + return one; } - const status = - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error?.response?.status ?? error?.status; - if (status && async_caller_STATUS_NO_RETRY.includes(+status)) { - throw error; + if (lastDigit >= 2 && lastDigit <= 4) { + return few; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.error?.code === "insufficient_quota") { - const err = new Error(error?.message); - err.name = "InsufficientQuotaError"; - throw err; + return many; +} +const ru_error = () => { + const Sizable = { + string: { + unit: { + one: "символ", + few: "символа", + many: "символов", + }, + verb: "иметь", + }, + file: { + unit: { + one: "байт", + few: "байта", + many: "байт", + }, + verb: "иметь", + }, + array: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов", + }, + verb: "иметь", + }, + set: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов", + }, + verb: "иметь", + }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "массив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ввод", + email: "email адрес", + url: "URL", + emoji: "эмодзи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата и время", + date: "ISO дата", + time: "ISO время", + duration: "ISO длительность", + ipv4: "IPv4 адрес", + ipv6: "IPv6 адрес", + cidrv4: "IPv4 диапазон", + cidrv6: "IPv6 диапазон", + base64: "строка в формате base64", + base64url: "строка в формате base64url", + json_string: "JSON строка", + e164: "номер E.164", + jwt: "JWT", + template_literal: "ввод", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Неверный ввод: ожидалось ${issue.expected}, получено ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Неверный ввод: ожидалось ${util.stringifyPrimitive(issue.values[0])}`; + return `Неверный вариант: ожидалось одно из ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + const maxValue = Number(issue.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`; + } + return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + const minValue = Number(issue.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`; + } + return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Неверная строка: должна начинаться с "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неверная строка: должна содержать "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; + return `Неверный ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Неверное число: должно быть кратным ${issue.divisor}`; + case "unrecognized_keys": + return `Нераспознанн${issue.keys.length > 1 ? "ые" : "ый"} ключ${issue.keys.length > 1 ? "и" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Неверный ключ в ${issue.origin}`; + case "invalid_union": + return "Неверные входные данные"; + case "invalid_element": + return `Неверное значение в ${issue.origin}`; + default: + return `Неверные входные данные`; + } + }; }; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class async_caller_AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = - params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); +/* harmony default export */ function ru() { + return { + localeError: ru_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/sl.js + +const sl_error = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "število"; } - else { - throw new Error(error); + case "object": { + if (Array.isArray(data)) { + return "tabela"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - }), { - onFailedAttempt: this.onFailedAttempt, - retries: this.maxRetries, - randomize: true, - // If needed we can change some of the defaults here, - // but they're quite sensible. - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res)))); - } + return t; + }; + const Nouns = { + regex: "vnos", + email: "e-poštni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in čas", + date: "ISO datum", + time: "ISO čas", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 številka", + jwt: "JWT", + template_literal: "vnos", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Neveljaven vnos: pričakovano ${issue.expected}, prejeto ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Neveljaven vnos: pričakovano ${util.stringifyPrimitive(issue.values[0])}`; + return `Neveljavna možnost: pričakovano eno izmed ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Premajhno: pričakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pričakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Neveljavno število: mora biti večkratnik ${issue.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue.keys.length > 1 ? "i ključi" : " ključ"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Neveljaven ključ v ${issue.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue.origin}`; + default: + return "Neveljaven vnos"; + } + }; +}; +/* harmony default export */ function sl() { + return { + localeError: sl_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/sv.js -class RootListenersTracer extends BaseTracer { - constructor({ config, onStart, onEnd, onError, }) { - super({ _awaitHandler: true }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "RootListenersTracer" - }); - /** The Run's ID. Type UUID */ - Object.defineProperty(this, "rootId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnStart", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnEnd", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "argOnError", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.config = config; - this.argOnStart = onStart; - this.argOnEnd = onEnd; - this.argOnError = onError; - } - /** - * This is a legacy method only called once for an entire run tree - * therefore not useful here - * @param {Run} _ Not used - */ - persistRun(_) { - return Promise.resolve(); +const sv_error = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att innehålla" }, + set: { unit: "objekt", verb: "att innehålla" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onRunCreate(run) { - if (this.rootId) { - return; + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "antal"; + } + case "object": { + if (Array.isArray(data)) { + return "lista"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - this.rootId = run.id; - if (this.argOnStart) { - await this.argOnStart(run, this.config); + return t; + }; + const Nouns = { + regex: "reguljärt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad sträng", + base64url: "base64url-kodad sträng", + json_string: "JSON-sträng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ogiltig inmatning: förväntat ${issue.expected}, fick ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ogiltig inmatning: förväntat ${util.stringifyPrimitive(issue.values[0])}`; + return `Ogiltigt val: förväntade en av ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; + return `Ogiltig(t) ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt värde i ${issue.origin ?? "värdet"}`; + default: + return `Ogiltig input`; } + }; +}; +/* harmony default export */ function sv() { + return { + localeError: sv_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ta.js + +const ta_error = () => { + const Sizable = { + string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, + file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, + array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - async onRunUpdate(run) { - if (run.id !== this.rootId) { - return; - } - if (!run.error) { - if (this.argOnEnd) { - await this.argOnEnd(run, this.config); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்"; + } + case "object": { + if (Array.isArray(data)) { + return "அணி"; + } + if (data === null) { + return "வெறுமை"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } } - else if (this.argOnError) { - await this.argOnError(run, this.config); + return t; + }; + const Nouns = { + regex: "உள்ளீடு", + email: "மின்னஞ்சல் முகவரி", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO தேதி நேரம்", + date: "ISO தேதி", + time: "ISO நேரம்", + duration: "ISO கால அளவு", + ipv4: "IPv4 முகவரி", + ipv6: "IPv6 முகவரி", + cidrv4: "IPv4 வரம்பு", + cidrv6: "IPv6 வரம்பு", + base64: "base64-encoded சரம்", + base64url: "base64url-encoded சரம்", + json_string: "JSON சரம்", + e164: "E.164 எண்", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue.expected}, பெறப்பட்டது ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${util.stringifyPrimitive(issue.values[0])}`; + return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${util.joinValues(issue.values, "|")} இல் ஒன்று`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; + } + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; // + } + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; + if (_issue.format === "ends_with") + return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; + if (_issue.format === "includes") + return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; + if (_issue.format === "regex") + return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; + return `தவறான ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`; + case "unrecognized_keys": + return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? "கள்" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} இல் தவறான விசை`; + case "invalid_union": + return "தவறான உள்ளீடு"; + case "invalid_element": + return `${issue.origin} இல் தவறான மதிப்பு`; + default: + return `தவறான உள்ளீடு`; } - } + }; +}; +/* harmony default export */ function ta() { + return { + localeError: ta_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; -} -/** - * Utility to filter the root event in the streamEvents implementation. - * This is simply binding the arguments to the namespace to make save on - * a bit of typing in the streamEvents implementation. - * - * TODO: Refactor and remove. - */ -class _RootEventFilter { - constructor(fields) { - Object.defineProperty(this, "includeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "includeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeNames", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTypes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "excludeTags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.includeNames = fields.includeNames; - this.includeTypes = fields.includeTypes; - this.includeTags = fields.includeTags; - this.excludeNames = fields.excludeNames; - this.excludeTypes = fields.excludeTypes; - this.excludeTags = fields.excludeTags; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/th.js + +const th_error = () => { + const Sizable = { + string: { unit: "ตัวอักษร", verb: "ควรมี" }, + file: { unit: "ไบต์", verb: "ควรมี" }, + array: { unit: "รายการ", verb: "ควรมี" }, + set: { unit: "รายการ", verb: "ควรมี" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - includeEvent(event, rootType) { - let include = this.includeNames === undefined && - this.includeTypes === undefined && - this.includeTags === undefined; - const eventTags = event.tags ?? []; - if (this.includeNames !== undefined) { - include = include || this.includeNames.includes(event.name); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข"; + } + case "object": { + if (Array.isArray(data)) { + return "อาร์เรย์ (Array)"; + } + if (data === null) { + return "ไม่มีค่า (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.includeTypes !== undefined) { - include = include || this.includeTypes.includes(rootType); + return t; + }; + const Nouns = { + regex: "ข้อมูลที่ป้อน", + email: "ที่อยู่อีเมล", + url: "URL", + emoji: "อิโมจิ", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "วันที่เวลาแบบ ISO", + date: "วันที่แบบ ISO", + time: "เวลาแบบ ISO", + duration: "ช่วงเวลาแบบ ISO", + ipv4: "ที่อยู่ IPv4", + ipv6: "ที่อยู่ IPv6", + cidrv4: "ช่วง IP แบบ IPv4", + cidrv6: "ช่วง IP แบบ IPv6", + base64: "ข้อความแบบ Base64", + base64url: "ข้อความแบบ Base64 สำหรับ URL", + json_string: "ข้อความแบบ JSON", + e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", + jwt: "โทเคน JWT", + template_literal: "ข้อมูลที่ป้อน", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue.expected} แต่ได้รับ ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `ค่าไม่ถูกต้อง: ควรเป็น ${util.stringifyPrimitive(issue.values[0])}`; + return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "ไม่เกิน" : "น้อยกว่า"; + const sizing = getSizing(issue.origin); + if (sizing) + return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? "รายการ"}`; + return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "อย่างน้อย" : "มากกว่า"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; + if (_issue.format === "includes") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; + if (_issue.format === "regex") + return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; + return `รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`; + case "unrecognized_keys": + return `พบคีย์ที่ไม่รู้จัก: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `คีย์ไม่ถูกต้องใน ${issue.origin}`; + case "invalid_union": + return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; + case "invalid_element": + return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`; + default: + return `ข้อมูลไม่ถูกต้อง`; } - if (this.includeTags !== undefined) { - include = - include || eventTags.some((tag) => this.includeTags?.includes(tag)); + }; +}; +/* harmony default export */ function th() { + return { + localeError: th_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/tr.js + +const tr_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; } - if (this.excludeNames !== undefined) { - include = include && !this.excludeNames.includes(event.name); + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } } - if (this.excludeTypes !== undefined) { - include = include && !this.excludeTypes.includes(rootType); + } + return t; +}; +const tr_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmalı" }, + file: { unit: "bayt", verb: "olmalı" }, + array: { unit: "öğe", verb: "olmalı" }, + set: { unit: "öğe", verb: "olmalı" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO süre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aralığı", + cidrv6: "IPv6 aralığı", + base64: "base64 ile şifrelenmiş metin", + base64url: "base64url ile şifrelenmiş metin", + json_string: "JSON dizesi", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "Şablon dizesi", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Geçersiz değer: beklenen ${issue.expected}, alınan ${tr_parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Geçersiz değer: beklenen ${util.stringifyPrimitive(issue.values[0])}`; + return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "öğe"}`; + return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; + if (_issue.format === "ends_with") + return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Geçersiz metin: "${_issue.includes}" içermeli`; + if (_issue.format === "regex") + return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; + return `Geçersiz ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Geçersiz sayı: ${issue.divisor} ile tam bölünebilmeli`; + case "unrecognized_keys": + return `Tanınmayan anahtar${issue.keys.length > 1 ? "lar" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} içinde geçersiz anahtar`; + case "invalid_union": + return "Geçersiz değer"; + case "invalid_element": + return `${issue.origin} içinde geçersiz değer`; + default: + return `Geçersiz değer`; + } + }; +}; +/* harmony default export */ function tr() { + return { + localeError: tr_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ua.js + +const ua_error = () => { + const Sizable = { + string: { unit: "символів", verb: "матиме" }, + file: { unit: "байтів", verb: "матиме" }, + array: { unit: "елементів", verb: "матиме" }, + set: { unit: "елементів", verb: "матиме" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "масив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "вхідні дані", + email: "адреса електронної пошти", + url: "URL", + emoji: "емодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "дата та час ISO", + date: "дата ISO", + time: "час ISO", + duration: "тривалість ISO", + ipv4: "адреса IPv4", + ipv6: "адреса IPv6", + cidrv4: "діапазон IPv4", + cidrv6: "діапазон IPv6", + base64: "рядок у кодуванні base64", + base64url: "рядок у кодуванні base64url", + json_string: "рядок JSON", + e164: "номер E.164", + jwt: "JWT", + template_literal: "вхідні дані", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${parsedType(issue.input)}`; + // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Неправильні вхідні дані: очікується ${util.stringifyPrimitive(issue.values[0])}`; + return `Неправильна опція: очікується одне з ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Занадто велике: очікується, що ${issue.origin ?? "значення"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементів"}`; + return `Занадто велике: очікується, що ${issue.origin ?? "значення"} буде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Занадто мале: очікується, що ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Занадто мале: очікується, що ${issue.origin} буде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неправильний рядок: повинен містити "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; + return `Неправильний ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Неправильне число: повинно бути кратним ${issue.divisor}`; + case "unrecognized_keys": + return `Нерозпізнаний ключ${issue.keys.length > 1 ? "і" : ""}: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Неправильний ключ у ${issue.origin}`; + case "invalid_union": + return "Неправильні вхідні дані"; + case "invalid_element": + return `Неправильне значення у ${issue.origin}`; + default: + return `Неправильні вхідні дані`; + } + }; +}; +/* harmony default export */ function ua() { + return { + localeError: ua_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/ur.js + +const ur_error = () => { + const Sizable = { + string: { unit: "حروف", verb: "ہونا" }, + file: { unit: "بائٹس", verb: "ہونا" }, + array: { unit: "آئٹمز", verb: "ہونا" }, + set: { unit: "آئٹمز", verb: "ہونا" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "نمبر"; + } + case "object": { + if (Array.isArray(data)) { + return "آرے"; + } + if (data === null) { + return "نل"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } } - if (this.excludeTags !== undefined) { - include = - include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); + return t; + }; + const Nouns = { + regex: "ان پٹ", + email: "ای میل ایڈریس", + url: "یو آر ایل", + emoji: "ایموجی", + uuid: "یو یو آئی ڈی", + uuidv4: "یو یو آئی ڈی وی 4", + uuidv6: "یو یو آئی ڈی وی 6", + nanoid: "نینو آئی ڈی", + guid: "جی یو آئی ڈی", + cuid: "سی یو آئی ڈی", + cuid2: "سی یو آئی ڈی 2", + ulid: "یو ایل آئی ڈی", + xid: "ایکس آئی ڈی", + ksuid: "کے ایس یو آئی ڈی", + datetime: "آئی ایس او ڈیٹ ٹائم", + date: "آئی ایس او تاریخ", + time: "آئی ایس او وقت", + duration: "آئی ایس او مدت", + ipv4: "آئی پی وی 4 ایڈریس", + ipv6: "آئی پی وی 6 ایڈریس", + cidrv4: "آئی پی وی 4 رینج", + cidrv6: "آئی پی وی 6 رینج", + base64: "بیس 64 ان کوڈڈ سٹرنگ", + base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", + json_string: "جے ایس او این سٹرنگ", + e164: "ای 164 نمبر", + jwt: "جے ڈبلیو ٹی", + template_literal: "ان پٹ", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `غلط ان پٹ: ${issue.expected} متوقع تھا، ${parsedType(issue.input)} موصول ہوا`; + case "invalid_value": + if (issue.values.length === 1) + return `غلط ان پٹ: ${util.stringifyPrimitive(issue.values[0])} متوقع تھا`; + return `غلط آپشن: ${util.joinValues(issue.values, "|")} میں سے ایک متوقع تھا`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; + return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; + } + return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; + } + if (_issue.format === "ends_with") + return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; + if (_issue.format === "includes") + return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; + if (_issue.format === "regex") + return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; + return `غلط ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`; + case "unrecognized_keys": + return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${util.joinValues(issue.keys, "، ")}`; + case "invalid_key": + return `${issue.origin} میں غلط کی`; + case "invalid_union": + return "غلط ان پٹ"; + case "invalid_element": + return `${issue.origin} میں غلط ویلیو`; + default: + return `غلط ان پٹ`; } - return include; - } + }; +}; +/* harmony default export */ function ur() { + return { + localeError: ur_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/Options.js -const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); -const jsonDescription = (jsonSchema, def) => { - if (def.description) { - try { - return { - ...jsonSchema, - ...JSON.parse(def.description), - }; - } - catch { } +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/vi.js + +const vi_error = () => { + const Sizable = { + string: { unit: "ký tự", verb: "có" }, + file: { unit: "byte", verb: "có" }, + array: { unit: "phần tử", verb: "có" }, + set: { unit: "phần tử", verb: "có" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } - return jsonSchema; -}; -const Options_defaultOptions = { - name: undefined, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "số"; + } + case "object": { + if (Array.isArray(data)) { + return "mảng"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "đầu vào", + email: "địa chỉ email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ngày giờ ISO", + date: "ngày ISO", + time: "giờ ISO", + duration: "khoảng thời gian ISO", + ipv4: "địa chỉ IPv4", + ipv6: "địa chỉ IPv6", + cidrv4: "dải IPv4", + cidrv6: "dải IPv6", + base64: "chuỗi mã hóa base64", + base64url: "chuỗi mã hóa base64url", + json_string: "chuỗi JSON", + e164: "số E.164", + jwt: "JWT", + template_literal: "đầu vào", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Đầu vào không hợp lệ: mong đợi ${issue.expected}, nhận được ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Đầu vào không hợp lệ: mong đợi ${util.stringifyPrimitive(issue.values[0])}`; + return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "phần tử"}`; + return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} không hợp lệ`; + } + case "not_multiple_of": + return `Số không hợp lệ: phải là bội số của ${issue.divisor}`; + case "unrecognized_keys": + return `Khóa không được nhận dạng: ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Khóa không hợp lệ trong ${issue.origin}`; + case "invalid_union": + return "Đầu vào không hợp lệ"; + case "invalid_element": + return `Giá trị không hợp lệ trong ${issue.origin}`; + default: + return `Đầu vào không hợp lệ`; + } + }; }; -const getDefaultOptions = (options) => (typeof options === "string" - ? { - ...Options_defaultOptions, - name: options, - } - : { - ...Options_defaultOptions, - ...options, - }); +/* harmony default export */ function vi() { + return { + localeError: vi_error(), + }; +} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/Refs.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/zh-CN.js -const getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== undefined - ? [..._options.basePath, _options.definitionPath, _options.name] - : _options.basePath; - return { - ..._options, - currentPath: currentPath, - propertyPath: undefined, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - def._def, - { - def: def._def, - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: undefined, - }, - ])), +const zh_CN_error = () => { + const Sizable = { + string: { unit: "字符", verb: "包含" }, + file: { unit: "字节", verb: "包含" }, + array: { unit: "项", verb: "包含" }, + set: { unit: "项", verb: "包含" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "非数字(NaN)" : "数字"; + } + case "object": { + if (Array.isArray(data)) { + return "数组"; + } + if (data === null) { + return "空值(null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "输入", + email: "电子邮件", + url: "URL", + emoji: "表情符号", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日期时间", + date: "ISO日期", + time: "ISO时间", + duration: "ISO时长", + ipv4: "IPv4地址", + ipv6: "IPv6地址", + cidrv4: "IPv4网段", + cidrv6: "IPv6网段", + base64: "base64编码字符串", + base64url: "base64url编码字符串", + json_string: "JSON字符串", + e164: "E.164号码", + jwt: "JWT", + template_literal: "输入", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `无效输入:期望 ${issue.expected},实际接收 ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `无效输入:期望 ${util.stringifyPrimitive(issue.values[0])}`; + return `无效选项:期望以下之一 ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "个元素"}`; + return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `无效字符串:必须以 "${_issue.prefix}" 开头`; + if (_issue.format === "ends_with") + return `无效字符串:必须以 "${_issue.suffix}" 结尾`; + if (_issue.format === "includes") + return `无效字符串:必须包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; + return `无效${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `无效数字:必须是 ${issue.divisor} 的倍数`; + case "unrecognized_keys": + return `出现未知的键(key): ${util.joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} 中的键(key)无效`; + case "invalid_union": + return "无效输入"; + case "invalid_element": + return `${issue.origin} 中包含无效值(value)`; + default: + return `无效输入`; + } }; }; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/any.js -function parseAnyDef() { - return {}; +/* harmony default export */ function zh_CN() { + return { + localeError: zh_CN_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/errorMessages.js -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage, - }; +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/zh-TW.js + +const zh_TW_error = () => { + const Sizable = { + string: { unit: "字元", verb: "擁有" }, + file: { unit: "位元組", verb: "擁有" }, + array: { unit: "項目", verb: "擁有" }, + set: { unit: "項目", verb: "擁有" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; } -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "輸入", + email: "郵件地址", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 日期時間", + date: "ISO 日期", + time: "ISO 時間", + duration: "ISO 期間", + ipv4: "IPv4 位址", + ipv6: "IPv6 位址", + cidrv4: "IPv4 範圍", + cidrv6: "IPv6 範圍", + base64: "base64 編碼字串", + base64url: "base64url 編碼字串", + json_string: "JSON 字串", + e164: "E.164 數值", + jwt: "JWT", + template_literal: "輸入", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `無效的輸入值:預期為 ${issue.expected},但收到 ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `無效的輸入值:預期為 ${util.stringifyPrimitive(issue.values[0])}`; + return `無效的選項:預期為以下其中之一 ${util.joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()} ${sizing.unit ?? "個元素"}`; + return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `無效的字串:必須以 "${_issue.prefix}" 開頭`; + } + if (_issue.format === "ends_with") + return `無效的字串:必須以 "${_issue.suffix}" 結尾`; + if (_issue.format === "includes") + return `無效的字串:必須包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `無效的字串:必須符合格式 ${_issue.pattern}`; + return `無效的 ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `無效的數字:必須為 ${issue.divisor} 的倍數`; + case "unrecognized_keys": + return `無法識別的鍵值${issue.keys.length > 1 ? "們" : ""}:${util.joinValues(issue.keys, "、")}`; + case "invalid_key": + return `${issue.origin} 中有無效的鍵值`; + case "invalid_union": + return "無效的輸入值"; + case "invalid_element": + return `${issue.origin} 中有無效的值`; + default: + return `無效的輸入值`; + } + }; +}; +/* harmony default export */ function zh_TW() { + return { + localeError: zh_TW_error(), + }; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/array.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/locales/index.js -function parseArrayDef(def, refs) { - const res = { - type: "array", - }; - if (def.type?._def && - def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { - res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"], - }); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/registries.js +const $output = Symbol("ZodOutput"); +const $input = Symbol("ZodInput"); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); } - if (def.minLength) { - setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema); + } + return this; } - if (def.maxLength) { - setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + remove(schema) { + this._map.delete(schema); + return this; } - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + return { ...pm, ...this._map.get(schema) }; + } + return this._map.get(schema); } - return res; + has(schema) { + return this._map.has(schema); + } +} +// registries +function registry() { + return new $ZodRegistry(); } +const globalRegistry = /*@__PURE__*/ registry(); -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/api.js -function parseBigintDef(def, refs) { - const res = { - type: "integer", + + +function _string(Class, params) { + return new Class({ + type: "string", + ...util.normalizeParams(params), + }); +} +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...util.normalizeParams(params), + }); +} +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...util.normalizeParams(params), + }); +} +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...util.normalizeParams(params), + }); +} +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +const TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +}; +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...util.normalizeParams(params), + }); +} +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...util.normalizeParams(params), + }); +} +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...util.normalizeParams(params), + }); +} +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...util.normalizeParams(params), + }); +} +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...util.normalizeParams(params), + }); +} +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...util.normalizeParams(params), + }); +} +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...util.normalizeParams(params), + }); +} +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...util.normalizeParams(params), + }); +} +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, format: "int64", - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; + ...util.normalizeParams(params), + }); +} +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +function api_null(Class, params) { + return new Class({ + type: "null", + ...util.normalizeParams(params), + }); +} +function _any(Class) { + return new Class({ + type: "any", + }); +} +function api_unknown(Class) { + return new Class({ + type: "unknown", + }); +} +function _never(Class, params) { + return new Class({ + type: "never", + ...util.normalizeParams(params), + }); +} +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +function _lt(value, params) { + return new checks.$ZodCheckLessThan({ + check: "less_than", + ...util.normalizeParams(params), + value, + inclusive: false, + }); +} +function _lte(value, params) { + return new checks.$ZodCheckLessThan({ + check: "less_than", + ...util.normalizeParams(params), + value, + inclusive: true, + }); +} + +function _gt(value, params) { + return new checks.$ZodCheckGreaterThan({ + check: "greater_than", + ...util.normalizeParams(params), + value, + inclusive: false, + }); +} +function _gte(value, params) { + return new checks.$ZodCheckGreaterThan({ + check: "greater_than", + ...util.normalizeParams(params), + value, + inclusive: true, + }); +} + +function _positive(params) { + return _gt(0, params); +} +// negative +function _negative(params) { + return _lt(0, params); +} +// nonpositive +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +function _nonnegative(params) { + return _gte(0, params); +} +function _multipleOf(value, params) { + return new checks.$ZodCheckMultipleOf({ + check: "multiple_of", + ...util.normalizeParams(params), + value, + }); +} +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +function _maxLength(maximum, params) { + const ch = new checks.$ZodCheckMaxLength({ + check: "max_length", + ...util.normalizeParams(params), + maximum, + }); + return ch; +} +function _minLength(minimum, params) { + return new checks.$ZodCheckMinLength({ + check: "min_length", + ...util.normalizeParams(params), + minimum, + }); +} +function _length(length, params) { + return new checks.$ZodCheckLengthEquals({ + check: "length_equals", + ...util.normalizeParams(params), + length, + }); +} +function _regex(pattern, params) { + return new checks.$ZodCheckRegex({ + check: "string_format", + format: "regex", + ...util.normalizeParams(params), + pattern, + }); +} +function _lowercase(params) { + return new checks.$ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...util.normalizeParams(params), + }); +} +function _uppercase(params) { + return new checks.$ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...util.normalizeParams(params), + }); +} +function _includes(includes, params) { + return new checks.$ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...util.normalizeParams(params), + includes, + }); +} +function _startsWith(prefix, params) { + return new checks.$ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...util.normalizeParams(params), + prefix, + }); +} +function _endsWith(suffix, params) { + return new checks.$ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...util.normalizeParams(params), + suffix, + }); +} +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +function _overwrite(tx) { + return new checks.$ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +function api_array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...util.normalizeParams(params), + }); +} +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options, + discriminator, + ...util.normalizeParams(params), + }); +} +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +function api_tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + }, + }); +} +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), + }); +} +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); } - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js -function parseBooleanDef() { - return { - type: "boolean", - }; +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); } - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js - -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// export function _refine( +// Class: util.SchemaClass, +// fn: (arg: NoInfer) => util.MaybeAsync, +// _params: string | $ZodCustomParams = {} +// ): checks.$ZodCheck { +// return _custom(Class, fn, _params); +// } +// same as _custom but deafults to abort:false +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...util.normalizeParams(_params), + }); + return schema; +} +function _stringbool(Classes, _params) { + const { case: _case, error, truthy, falsy } = util.normalizeParams(_params); + let truthyArray = truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (_case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Pipe = Classes.Pipe ?? schemas.$ZodPipe; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const _Transform = Classes.Transform ?? schemas.$ZodTransform; + const tx = new _Transform({ + type: "transform", + transform: (input, payload) => { + let data = input; + if (_case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: tx, + }); + return {}; + } + }, + error, + }); + const innerPipe = new _Pipe({ + type: "pipe", + in: new _String({ type: "string", error }), + out: tx, + error, + }); + const outerPipe = new _Pipe({ + type: "pipe", + in: innerPipe, + out: new _Boolean({ + type: "boolean", + error, + }), + error, + }); + return outerPipe; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/function.js -const parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/date.js -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), - }; - } - switch (strategy) { - case "string": - case "format:date-time": - return { - type: "string", - format: "date-time", - }; - case "format:date": - return { - type: "string", - format: "date", - }; - case "integer": - return integerDateParser(def, refs); - } -} -const integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time", - }; - if (refs.target === "openApi3") { - return res; + +class $ZodFunction { + constructor(def) { + this._def = def; + this.def = def; } - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minimum", check.value, // This is in milliseconds - check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maximum", check.value, // This is in milliseconds - check.message, refs); - break; + implement(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = ((...args) => { + const parsedArgs = this._def.input ? parse(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = func(...parsedArgs); + return this._def.output ? parse(this._def.output, output, undefined, { callee: impl }) : output; + }); + return impl; + } + implementAsync(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = (async (...args) => { + const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, undefined, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = await func(...parsedArgs); + return this._def.output ? parseAsync(this._def.output, output, undefined, { callee: impl }) : output; + }); + return impl; + } + input(...args) { + const F = this.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: this._def.output, + }); } + return new F({ + type: "function", + input: args[0], + output: this._def.output, + }); + } + output(output) { + const F = this.constructor; + return new F({ + type: "function", + input: this._def.input, + output, + }); } - return res; -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/default.js - -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue(), - }; } - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js - -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" - ? parseDef(_def.schema._def, refs) - : {}; +function _function(params) { + return new $ZodFunction({ + type: "function", + input: Array.isArray(params?.input) + ? _tuple(schemas.$ZodTuple, params?.input) + : (params?.input ?? _array(schemas.$ZodArray, _unknown(schemas.$ZodUnknown))), + output: params?.output ?? _unknown(schemas.$ZodUnknown), + }); } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values), - }; -} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/to-json-schema.js -const isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") - return false; - return "allOf" in type; -}; -function parseIntersectionDef(def, refs) { - const allOf = [ - parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"], - }), - parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "1"], - }), - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" - ? { unevaluatedProperties: false } - : undefined; - const mergedAllOf = []; - // If either of the schemas is an allOf, merge them into a single allOf - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === undefined) { - // If one of the schemas has no unevaluatedProperties set, - // the merged schema should also have no unevaluatedProperties set - unevaluatedProperties = undefined; - } + +class JSONSchemaGenerator { + constructor(params) { + this.counter = 0; + this.metadataRegistry = params?.metadata ?? globalRegistry; + this.target = params?.target ?? "draft-2020-12"; + this.unrepresentable = params?.unrepresentable ?? "throw"; + this.override = params?.override ?? (() => { }); + this.io = params?.io ?? "output"; + this.seen = new Map(); + } + process(schema, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set + }; + // check for schema in seens + const seen = this.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined }; + this.seen.set(schema, result); + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; } else { - let nestedSchema = schema; - if ("additionalProperties" in schema && - schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + const parent = schema._zod.parent; + if (parent) { + // schema was cloned from another schema + result.ref = parent; + this.process(parent, params); + this.seen.get(parent).isParent = true; } else { - // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties - unevaluatedProperties = undefined; + const _json = result.schema; + switch (def.type) { + case "string": { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json.pattern = regexes[0].source; + else if (regexes.length > 1) { + result.schema.allOf = [ + ...regexes.map((regex) => ({ + ...(this.target === "draft-7" ? { type: "string" } : {}), + pattern: regex.source, + })), + ]; + } + } + break; + } + case "number": { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + if (typeof exclusiveMinimum === "number") + json.exclusiveMinimum = exclusiveMinimum; + if (typeof minimum === "number") { + json.minimum = minimum; + if (typeof exclusiveMinimum === "number") { + if (exclusiveMinimum >= minimum) + delete json.minimum; + else + delete json.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") + json.exclusiveMaximum = exclusiveMaximum; + if (typeof maximum === "number") { + json.maximum = maximum; + if (typeof exclusiveMaximum === "number") { + if (exclusiveMaximum <= maximum) + delete json.maximum; + else + delete json.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json.multipleOf = multipleOf; + break; + } + case "boolean": { + const json = _json; + json.type = "boolean"; + break; + } + case "bigint": { + if (this.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + break; + } + case "symbol": { + if (this.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + break; + } + case "undefined": { + const json = _json; + json.type = "null"; + break; + } + case "null": { + _json.type = "null"; + break; + } + case "any": { + break; + } + case "unknown": { + break; + } + case "never": { + _json.not = {}; + break; + } + case "void": { + if (this.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + break; + } + case "date": { + if (this.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + break; + } + case "array": { + const json = _json; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); + break; + } + case "object": { + const json = _json; + json.type = "object"; + json.properties = {}; + const shape = def.shape; // params.shapeCache.get(schema)!; + for (const key in shape) { + json.properties[key] = this.process(shape[key], { + ...params, + path: [...params.path, "properties", key], + }); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + // const optionalKeys = new Set(def.optional); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (this.io === "input") { + return v.optin === undefined; + } + else { + return v.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (this.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = this.process(def.catchall, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + break; + } + case "union": { + const json = _json; + json.anyOf = def.options.map((x, i) => this.process(x, { + ...params, + path: [...params.path, "anyOf", i], + })); + break; + } + case "intersection": { + const json = _json; + const a = this.process(def.left, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = this.process(def.right, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + break; + } + case "tuple": { + const json = _json; + json.type = "array"; + const prefixItems = def.items.map((x, i) => this.process(x, { ...params, path: [...params.path, "prefixItems", i] })); + if (this.target === "draft-2020-12") { + json.prefixItems = prefixItems; + } + else { + json.items = prefixItems; + } + if (def.rest) { + const rest = this.process(def.rest, { + ...params, + path: [...params.path, "items"], + }); + if (this.target === "draft-2020-12") { + json.items = rest; + } + else { + json.additionalItems = rest; + } + } + // additionalItems + if (def.rest) { + json.items = this.process(def.rest, { + ...params, + path: [...params.path, "items"], + }); + } + // length + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + break; + } + case "record": { + const json = _json; + json.type = "object"; + json.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); + json.additionalProperties = this.process(def.valueType, { + ...params, + path: [...params.path, "additionalProperties"], + }); + break; + } + case "map": { + if (this.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + break; + } + case "set": { + if (this.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + break; + } + case "enum": { + const json = _json; + const values = getEnumValues(def.entries); + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; + break; + } + case "literal": { + const json = _json; + const vals = []; + for (const val of def.values) { + if (val === undefined) { + if (this.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } + else { + // do not add to vals + } + } + else if (typeof val === "bigint") { + if (this.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } + else { + vals.push(Number(val)); + } + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + json.const = val; + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "string"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } + break; + } + case "file": { + const json = _json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(json, file); + } + else { + json.anyOf = mime.map((m) => { + const mFile = { ...file, contentMediaType: m }; + return mFile; + }); + } + } + else { + Object.assign(json, file); + } + // if (this.unrepresentable === "throw") { + // throw new Error("File cannot be represented in JSON Schema"); + // } + break; + } + case "transform": { + if (this.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + break; + } + case "nullable": { + const inner = this.process(def.innerType, params); + _json.anyOf = [inner, { type: "null" }]; + break; + } + case "nonoptional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "success": { + const json = _json; + json.type = "boolean"; + break; + } + case "default": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.default = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "prefault": { + this.process(def.innerType, params); + result.ref = def.innerType; + if (this.io === "input") + _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "catch": { + // use conditionals + this.process(def.innerType, params); + result.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + _json.default = catchValue; + break; + } + case "nan": { + if (this.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + break; + } + case "template_literal": { + const json = _json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + json.type = "string"; + json.pattern = pattern.source; + break; + } + case "pipe": { + const innerType = this.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "readonly": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.readOnly = true; + break; + } + // passthrough types + case "promise": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "optional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "lazy": { + const innerType = schema._zod.innerType; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "custom": { + if (this.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + break; + } + default: { + def; + } + } } - mergedAllOf.push(nestedSchema); } - }); - return mergedAllOf.length - ? { - allOf: mergedAllOf, - ...unevaluatedProperties, + // metadata + const meta = this.metadataRegistry.get(schema); + if (meta) + Object.assign(result.schema, meta); + if (this.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; } - : undefined; -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && - parsedType !== "number" && - parsedType !== "boolean" && - parsedType !== "string") { - return { - type: Array.isArray(def.value) ? "array" : "object", - }; + // set prefault as default + if (this.io === "input" && result.schema._prefault) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from this.seen in case it was overwritten + const _result = this.seen.get(schema); + return _result.schema; } - if (refs.target === "openApi3") { - return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value], + emit(schema, _params) { + const params = { + cycles: _params?.cycles ?? "ref", + reused: _params?.reused ?? "inline", + // unrepresentable: _params?.unrepresentable ?? "throw", + // uri: _params?.uri ?? ((id) => `${id}`), + external: _params?.external ?? undefined, }; - } - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value, - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/string.js - -let string_emojiRegex = undefined; -/** - * Generated from the regular expressions found here as of 2024-05-22: - * https://github.com/colinhacks/zod/blob/master/src/types.ts. - * - * Expressions with /i flag have been changed accordingly. - */ -const zodPatterns = { - /** - * `c` was changed to `[cC]` to replicate /i flag - */ - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - /** - * `a-z` was added to replicate /i flag - */ - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - /** - * Constructed a valid Unicode RegExp - * - * Lazily instantiate since this type of regex isn't supported - * in all envs (e.g. React Native). - * - * See: - * https://github.com/colinhacks/zod/issues/2433 - * Fix in Zod: - * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b - */ - emoji: () => { - if (string_emojiRegex === undefined) { - string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - } - return string_emojiRegex; - }, - /** - * Unused - */ - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - /** - * Unused - */ - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - /** - * Unused - */ - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, -}; -function parseStringDef(def, refs) { - const res = { - type: "string", - }; - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" - ? Math.max(res.minLength, check.value) - : check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" - ? Math.min(res.maxLength, check.value) - : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex, check.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "date": - addFormat(res, "date", check.message, refs); - break; - case "time": - addFormat(res, "time", check.message, refs); - break; - case "duration": - addFormat(res, "duration", check.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" - ? Math.max(res.minLength, check.value) - : check.value, check.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" - ? Math.min(res.maxLength, check.value) - : check.value, check.message, refs); - break; - case "includes": { - addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); - break; + // iterate over seen map; + const root = this.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // initialize result with root schema fields + // Object.assign(result, seen.cached); + const makeURI = (entry) => { + // comparing the seen objects because sometimes + // multiple schemas map to the same seen object. + // e.g. lazy + // external is configured + const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; + if (params.external) { + const externalId = params.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${this.counter++}`; + // check if schema is in the external registry + if (externalId) + return { ref: params.external.uri(externalId) }; + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${params.external.uri("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + // self-contained schema + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${this.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + // stored cached version in `def` property + // remove all properties, set $ref + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // extract schemas into $defs + for (const entry of this.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + // also prevents root schema from being extracted + if (schema === entry[0]) { + // do not copy to defs...this is the root schema + extractToDef(entry); + continue; + } + // extract schemas that are in the external registry + if (params.external) { + const ext = params.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; } - case "ip": { - if (check.version !== "v6") { - addFormat(res, "ipv4", check.message, refs); - } - if (check.version !== "v4") { - addFormat(res, "ipv6", check.message, refs); - } - break; + } + // extract schemas with `id` meta + const id = this.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + if (params.cycles === "throw") { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); } - case "base64url": - addPattern(res, zodPatterns.base64url, check.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check.message, refs); - break; - case "cidr": { - if (check.version !== "v6") { - addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); - } - if (check.version !== "v4") { - addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); - } - break; + else if (params.cycles === "ref") { + extractToDef(entry); } - case "emoji": - addPattern(res, zodPatterns.emoji(), check.message, refs); - break; - case "ulid": { - addPattern(res, zodPatterns.ulid, check.message, refs); - break; + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (params.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; } - case "base64": { - switch (refs.base64Strategy) { - case "format:binary": { - addFormat(res, "binary", check.message, refs); - break; - } - case "contentEncoding:base64": { - setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); - break; - } - case "pattern:zod": { - addPattern(res, zodPatterns.base64, check.message, refs); - break; - } - } - break; + } + } + // flatten _refs + const flattenRef = (zodSchema, params) => { + const seen = this.seen.get(zodSchema); + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + // already seen + if (seen.ref === null) { + return; + } + // flatten ref if defined + const ref = seen.ref; + seen.ref = null; // prevent recursion + if (ref) { + flattenRef(ref, params); + // merge referenced schema into current + const refSchema = this.seen.get(ref).schema; + if (refSchema.$ref && params.target === "draft-7") { + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); } - case "nanoid": { - addPattern(res, zodPatterns.nanoid, check.message, refs); + else { + Object.assign(schema, refSchema); + Object.assign(schema, _cached); // prevent overwriting any fields in the original schema } - case "toLowerCase": - case "toUpperCase": - case "trim": - break; - default: - /* c8 ignore next */ - ((_) => { })(check); } + // execute overrides + if (!seen.isParent) + this.override({ + zodSchema: zodSchema, + jsonSchema: schema, + }); + }; + for (const entry of [...this.seen.entries()].reverse()) { + flattenRef(entry[0], { target: this.target }); } - } - return res; -} -function escapeLiteralCheckValue(literal, refs) { - return refs.patternStrategy === "escape" - ? escapeNonAlphaNumeric(literal) - : literal; -} -const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i = 0; i < source.length; i++) { - if (!ALPHA_NUMERIC.has(source[i])) { - result += "\\"; + const result = {}; + if (this.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; } - result += source[i]; - } - return result; -} -// Adds a "format" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones. -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) { - schema.anyOf = []; + else if (this.target === "draft-7") { + result.$schema = "http://json-schema.org/draft-07/schema#"; } - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format }, - }), - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } + else { + console.warn(`Invalid target: ${this.target}`); + } + Object.assign(result, root.def); + // build defs object + const defs = params.external?.defs ?? {}; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; } } - schema.anyOf.push({ - format: value, - ...(message && - refs.errorMessages && { errorMessage: { format: message } }), - }); - } - else { - setResponseValueAndErrors(schema, "format", value, message, refs); + // set definitions in result + if (!params.external && Object.keys(defs).length > 0) { + if (this.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed + // each call to .emit() is functionally independent + // though the seen map is shared + return JSON.parse(JSON.stringify(result)); + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } } } -// Adds a "pattern" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones. -function addPattern(schema, regex, message, refs) { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) { - schema.allOf = []; +function toJSONSchema(input, _params) { + if (input instanceof $ZodRegistry) { + const gen = new JSONSchemaGenerator(_params); + const defs = {}; + for (const entry of input._idmap.entries()) { + const [_, schema] = entry; + gen.process(schema); } - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern }, - }), + const schemas = {}; + const external = { + registry: input, + uri: _params?.uri || ((id) => id), + defs, + }; + for (const entry of input._idmap.entries()) { + const [key, schema] = entry; + schemas[key] = gen.emit(schema, { + ..._params, + external, }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...(message && - refs.errorMessages && { errorMessage: { pattern: message } }), - }); - } - else { - setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + if (Object.keys(defs).length > 0) { + const defsSegment = gen.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; } + const gen = new JSONSchemaGenerator(_params); + gen.process(input); + return gen.emit(input, _params); } -// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) { - return regex.source; - } - // Currently handled flags - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s"), // `.` matches newlines - }; - // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const schema = _schema; + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "date": + case "symbol": + case "undefined": + case "null": + case "any": + case "unknown": + case "never": + case "void": + case "literal": + case "enum": + case "nan": + case "file": + case "template_literal": + return false; + case "array": { + return isTransforming(def.element, ctx); } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } - else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } - else { - pattern += `${source[i]}${source[i].toUpperCase()}`; - } - continue; - } - } - else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; + case "object": { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; } + return false; } - if (flags.m) { - if (source[i] === "^") { - pattern += `(^|(?<=[\r\n]))`; - continue; + case "union": { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; } - else if (source[i] === "$") { - pattern += `($|(?=[\r\n]))`; - continue; + return false; + } + case "intersection": { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + case "tuple": { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; } - if (flags.s && source[i] === ".") { - pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; - continue; + case "record": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } - pattern += source[i]; - if (source[i] === "\\") { - isEscaped = true; + case "map": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); } - else if (inCharGroup && source[i] === "]") { - inCharGroup = false; + case "set": { + return isTransforming(def.valueType, ctx); } - else if (!inCharGroup && source[i] === "[") { - inCharGroup = true; + // inner types + case "promise": + case "optional": + case "nonoptional": + case "nullable": + case "readonly": + return isTransforming(def.innerType, ctx); + case "lazy": + return isTransforming(def.getter(), ctx); + case "default": { + return isTransforming(def.innerType, ctx); } + case "prefault": { + return isTransforming(def.innerType, ctx); + } + case "custom": { + return false; + } + case "transform": { + return true; + } + case "pipe": { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + case "success": { + return false; + } + case "catch": { + return false; + } + default: + def; } - try { - new RegExp(pattern); - } - catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; + throw new Error(`Unknown schema type: ${def.type}`); } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/record.js +;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/index.js -function parseRecordDef(def, refs) { - if (refs.target === "openAi") { - console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - } - if (refs.target === "openApi3" && - def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", key], - }) ?? {}, - }), {}), - additionalProperties: refs.rejectedAdditionalProperties, - }; - } - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"], - }) ?? refs.allowedAdditionalProperties, - }; - if (refs.target === "openApi3") { - return schema; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && - def.keyType._def.checks?.length) { - const { type, ...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType, - }; - } - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - ...schema, - propertyNames: { - enum: def.keyType._def.values, - }, - }; - } - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && - def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && - def.keyType._def.type._def.checks?.length) { - const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType, - }; - } - return schema; -} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/map.js -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") { - return parseRecordDef(def, refs); - } - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "0"], - }) || {}; - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "1"], - }) || {}; - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2, - }, - }; -} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 - ? parsedTypes[0] === "string" - ? "string" - : "number" - : ["string", "number"], - enum: actualValues, - }; -} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/never.js -function parseNeverDef() { - return { - not: {}, - }; -} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/null.js -function parseNullDef(refs) { - return refs.target === "openApi3" - ? { - enum: ["null"], - nullable: true, - } - : { - type: "null", - }; -} -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/union.js -const primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null", -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. - if (options.every((x) => x._def.typeName in primitiveMappings && - (!x._def.checks || !x._def.checks.length))) { - // all types in union are primitive and lack checks, so might as well squash into {type: [...]} - const types = options.reduce((types, x) => { - const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 - return type && !types.includes(type) ? [...types, type] : types; - }, []); - return { - type: types.length > 1 ? types : types[0], - }; - } - else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - // all options literals - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": - return [...acc, type]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x._def.value === null) - return [...acc, "null"]; - case "symbol": - case "undefined": - case "function": - default: - return acc; - } - }, []); - if (types.length === options.length) { - // all the literals are primitive, as far as null can be considered primitive - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + + + + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/Options.js +const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); +const jsonDescription = (jsonSchema, def) => { + if (def.description) { + try { return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []), + ...jsonSchema, + ...JSON.parse(def.description), }; } + catch { } } - else if (options.every((x) => x._def.typeName === "ZodEnum")) { - return { - type: "string", - enum: options.reduce((acc, x) => [ - ...acc, - ...x._def.values.filter((x) => !acc.includes(x)), - ], []), - }; - } - return asAnyOf(def, refs); -} -const asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map - ? Array.from(def.options.values()) - : def.options) - .map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", `${i}`], - })) - .filter((x) => !!x && - (!refs.strictUnions || - (typeof x === "object" && Object.keys(x).length > 0))); - return anyOf.length ? { anyOf } : undefined; + return jsonSchema; +}; +const Options_defaultOptions = { + name: undefined, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", }; +const getDefaultOptions = (options) => (typeof options === "string" + ? { + ...Options_defaultOptions, + name: options, + } + : { + ...Options_defaultOptions, + ...options, + }); -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/Refs.js +const getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== undefined + ? [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + currentPath: currentPath, + propertyPath: undefined, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; -function parseNullableDef(def, refs) { - if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && - (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") { - return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true, - }; - } - return { - type: [ - primitiveMappings[def.innerType._def.typeName], - "null", - ], +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/any.js +function parseAnyDef() { + return {}; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/errorMessages.js +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, }; } - if (refs.target === "openApi3") { - const base = parseDef(def.innerType._def, { +} +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/array.js + + + +function parseArrayDef(def, refs) { + const res = { + type: "array", + }; + if (def.type?._def && + def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef(def.type._def, { ...refs, - currentPath: [...refs.currentPath], + currentPath: [...refs.currentPath, "items"], }); - if (base && "$ref" in base) - return { allOf: [base], nullable: true }; - return base && { ...base, nullable: true }; } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "0"], - }); - return base && { anyOf: [base, { type: "null" }] }; + if (def.minLength) { + setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/number.js +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js -function parseNumberDef(def, refs) { +function parseBigintDef(def, refs) { const res = { - type: "number", + type: "integer", + format: "int64", }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check.message, refs); - break; case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { @@ -97318,971 +106432,1273 @@ function parseNumberDef(def, refs) { return res; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/object.js - - -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {}, - }; - const required = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === undefined || propDef._def === undefined) { - continue; - } - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef instanceof ZodOptional) { - propDef = propDef._def.innerType; - } - if (!propDef.isNullable()) { - propDef = propDef.nullable(); - } - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", propName], - propertyPath: [...refs.currentPath, "properties", propName], - }); - if (parsedDef === undefined) { - continue; - } - result.properties[propName] = parsedDef; - if (!propOptional) { - required.push(propName); - } - } - if (required.length) { - result.required = required; - } - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== undefined) { - result.additionalProperties = additionalProperties; - } - return result; -} -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") { - return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"], - }); - } - switch (def.unknownKeys) { - case "passthrough": - return refs.allowedAdditionalProperties; - case "strict": - return refs.rejectedAdditionalProperties; - case "strip": - return refs.removeAdditionalStrategy === "strict" - ? refs.allowedAdditionalProperties - : refs.rejectedAdditionalProperties; - } -} -function safeIsOptional(schema) { - try { - return schema.isOptional(); - } - catch { - return true; - } -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js - -const parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) { - return parseDef(def.innerType._def, refs); - } - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "1"], - }); - return innerSchema - ? { - anyOf: [ - { - not: {}, - }, - innerSchema, - ], - } - : {}; -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js - -const parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") { - return parseDef(def.in._def, refs); - } - else if (refs.pipeStrategy === "output") { - return parseDef(def.out._def, refs); - } - const a = parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"], - }); - const b = parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"], - }); - return { - allOf: [a, b].filter((x) => x !== undefined), - }; -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js - -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/set.js - - -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"], - }); - const schema = { - type: "array", - uniqueItems: true, - items, - }; - if (def.minSize) { - setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js - -function parseTupleDef(def, refs) { - if (def.rest) { - return { - type: "array", - minItems: def.items.length, - items: def.items - .map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"], - }), - }; - } - else { - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items - .map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - }; - } -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js -function parseUndefinedDef() { +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js +function parseBooleanDef() { return { - not: {}, + type: "boolean", }; } -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js -function parseUnknownDef() { - return {}; -} - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js - -const parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/selectParser.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: - return parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: - return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: - return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: - return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: - return parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: - return parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: - return parseUndefinedDef(); - case ZodFirstPartyTypeKind.ZodNull: - return parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: - return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: - return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: - return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: - return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: - return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return () => def.getter()._def; - case ZodFirstPartyTypeKind.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return parseNeverDef(); - case ZodFirstPartyTypeKind.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: - return parseAnyDef(); - case ZodFirstPartyTypeKind.ZodUnknown: - return parseUnknownDef(); - case ZodFirstPartyTypeKind.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return undefined; - default: - /* c8 ignore next */ - return ((_) => undefined)(typeName); - } -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parseDef.js - +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/branded.js -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== undefined) { - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) - const jsonSchema = typeof jsonSchemaOrGetter === "function" - ? parseDef(jsonSchemaOrGetter(), refs) - : jsonSchemaOrGetter; - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); } -const get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return {}; - } - return refs.$refStrategy === "seen" ? {} : undefined; - } - } -}; -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; -const addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js - - -const zodToJsonSchema_zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - const definitions = typeof options === "object" && options.definitions - ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ - ...acc, - [name]: parseDef(schema._def, { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }, true) ?? {}, - }), {}) - : undefined; - const name = typeof options === "string" - ? options - : options?.nameStrategy === "title" - ? undefined - : options?.name; - const main = parseDef(schema._def, name === undefined - ? refs - : { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }, false) ?? {}; - const title = typeof options === "object" && - options.name !== undefined && - options.nameStrategy === "title" - ? options.name - : undefined; - if (title !== undefined) { - main.title = title; - } - const combined = name === undefined - ? definitions - ? { - ...main, - [refs.definitionPath]: definitions, - } - : main - : { - $ref: [ - ...(refs.$refStrategy === "relative" ? [] : refs.basePath), - refs.definitionPath, - name, - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main, - }, - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - } - if (refs.target === "openAi" && - ("anyOf" in combined || - "oneOf" in combined || - "allOf" in combined || - ("type" in combined && Array.isArray(combined.type)))) { - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - } - return combined; -}; - - -;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +const parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/date.js +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)), + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time", + }; + case "format:date": + return { + type: "string", + format: "date", + }; + case "integer": + return integerDateParser(def, refs); + } +} +const integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time", + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minimum", check.value, // This is in milliseconds + check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maximum", check.value, // This is in milliseconds + check.message, refs); + break; + } + } + return res; +}; +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/default.js +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" + ? parseDef(_def.schema._def, refs) + : {}; +} +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values), + }; +} -/* harmony default export */ const esm = ((/* unused pure expression or super */ null && (zodToJsonSchema))); +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js -function _escapeNodeLabel(nodeLabel) { - // Escapes the node label for Mermaid syntax. - return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +const isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"], + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"], + }), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" + ? { unevaluatedProperties: false } + : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } + else { + let nestedSchema = schema; + if ("additionalProperties" in schema && + schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length + ? { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; } -const MARKDOWN_SPECIAL_CHARS = ["*", "_", "`"]; -function _generateMermaidGraphStyles(nodeColors) { - let styles = ""; - for (const [className, color] of Object.entries(nodeColors)) { - styles += `\tclassDef ${className} ${color};\n`; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/literal.js +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && + parsedType !== "number" && + parsedType !== "boolean" && + parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object", + }; } - return styles; + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value], + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value, + }; } + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/string.js + +let string_emojiRegex = undefined; /** - * Draws a Mermaid graph using the provided graph data + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. */ -function drawMermaid(nodes, edges, config) { - const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9, } = config ?? {}; - // Initialize Mermaid graph configuration - let mermaidGraph = withStyles - ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` - : "graph TD;\n"; - if (withStyles) { - // Node formatting templates - const defaultClassLabel = "default"; - const formatDict = { - [defaultClassLabel]: "{0}({1})", - }; - if (firstNode !== undefined) { - formatDict[firstNode] = "{0}([{1}]):::first"; - } - if (lastNode !== undefined) { - formatDict[lastNode] = "{0}([{1}]):::last"; +const zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (string_emojiRegex === undefined) { + string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } - // Add nodes to the graph - for (const [key, node] of Object.entries(nodes)) { - const nodeName = node.name.split(":").pop() ?? ""; - const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) - ? `

${nodeName}

` - : nodeName; - let finalLabel = label; - if (Object.keys(node.metadata ?? {}).length) { - finalLabel += `
${Object.entries(node.metadata ?? {}) - .map(([k, v]) => `${k} = ${v}`) - .join("\n")}`; + return string_emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/, +}; +function parseStringDef(def, refs) { + const res = { + type: "string", + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" + ? Math.max(res.minLength, check.value) + : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" + ? Math.min(res.maxLength, check.value) + : check.value, check.message, refs); + break; + case "includes": { + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern(res, zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern(res, zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + /* c8 ignore next */ + ((_) => { })(check); } - const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]) - .replace("{0}", _escapeNodeLabel(key)) - .replace("{1}", finalLabel); - mermaidGraph += `\t${nodeLabel}\n`; } } - // Group edges by their common prefixes - const edgeGroups = {}; - for (const edge of edges) { - const srcParts = edge.source.split(":"); - const tgtParts = edge.target.split(":"); - const commonPrefix = srcParts - .filter((src, i) => src === tgtParts[i]) - .join(":"); - if (!edgeGroups[commonPrefix]) { - edgeGroups[commonPrefix] = []; + return res; +} +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" + ? escapeNonAlphaNumeric(literal) + : literal; +} +const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0; i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) { + result += "\\"; } - edgeGroups[commonPrefix].push(edge); + result += source[i]; } - const seenSubgraphs = new Set(); - function addSubgraph(edges, prefix) { - const selfLoop = edges.length === 1 && edges[0].source === edges[0].target; - if (prefix && !selfLoop) { - const subgraph = prefix.split(":").pop(); - if (seenSubgraphs.has(subgraph)) { - throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that ` + - "you're reusing a subgraph node with the same name. " + - "Please adjust your graph to have subgraph nodes with unique names."); + return result; +} +// Adds a "format" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones. +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } } - seenSubgraphs.add(subgraph); - mermaidGraph += `\tsubgraph ${subgraph}\n`; } - for (const edge of edges) { - const { source, target, data, conditional } = edge; - let edgeLabel = ""; - if (data !== undefined) { - let edgeData = data; - const words = edgeData.split(" "); - if (words.length > wrapLabelNWords) { - edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words - .slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords) - .join(" ")).join(" 
 "); + schema.anyOf.push({ + format: value, + ...(message && + refs.errorMessages && { errorMessage: { format: message } }), + }); + } + else { + setResponseValueAndErrors(schema, "format", value, message, refs); + } +} +// Adds a "pattern" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones. +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...(message && + refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } + else { + setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + } +} +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + // Currently handled flags + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s"), // `.` matches newlines + }; + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } + else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } + else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; } - edgeLabel = conditional - ? ` -.  ${edgeData}  .-> ` - : ` --  ${edgeData}  --> `; } - else { - edgeLabel = conditional ? " -.-> " : " --> "; + else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; } - mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; } - // Recursively add nested subgraphs - for (const nestedPrefix in edgeGroups) { - if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix) { - addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r\n]))`; + continue; + } + else if (source[i] === "$") { + pattern += `($|(?=[\r\n]))`; + continue; } } - if (prefix && !selfLoop) { - mermaidGraph += "\tend\n"; + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; } - } - // Start with the top-level edges (no common prefix) - addSubgraph(edgeGroups[""] ?? [], ""); - // Add remaining subgraphs - for (const prefix in edgeGroups) { - if (!prefix.includes(":") && prefix !== "") { - addSubgraph(edgeGroups[prefix], prefix); + pattern += source[i]; + if (source[i] === "\\") { + isEscaped = true; } - } - // Add custom styles for nodes - if (withStyles) { - mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); - } - return mermaidGraph; -} -/** - * Renders Mermaid graph using the Mermaid.INK API. - */ -async function drawMermaidPng(mermaidSyntax, config) { - let { backgroundColor = "white" } = config ?? {}; - // Use btoa for compatibility, assume ASCII - const mermaidSyntaxEncoded = btoa(mermaidSyntax); - // Check if the background color is a hexadecimal color code using regex - if (backgroundColor !== undefined) { - const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; - if (!hexColorPattern.test(backgroundColor)) { - backgroundColor = `!${backgroundColor}`; + else if (inCharGroup && source[i] === "]") { + inCharGroup = false; + } + else if (!inCharGroup && source[i] === "[") { + inCharGroup = true; } } - const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}`; - const res = await fetch(imageUrl); - if (!res.ok) { - throw new Error([ - `Failed to render the graph using the Mermaid.INK API.`, - `Status code: ${res.status}`, - `Status text: ${res.statusText}`, - ].join("\n")); + try { + new RegExp(pattern); } - const content = await res.blob(); - return content; + catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/record.js -function nodeDataStr(id, data) { - if (id !== undefined && !wrapper_validate(id)) { - return id; +function parseRecordDef(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); } - else if (isRunnableInterface(data)) { - try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") - ? dataStr.slice("Runnable".length) - : dataStr; - return dataStr; - } - catch (error) { - return data.getName(); - } + if (refs.target === "openApi3" && + def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key], + }) ?? {}, + }), {}), + additionalProperties: refs.rejectedAdditionalProperties, + }; } - else { - return data.name ?? "UnknownSchema"; + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"], + }) ?? refs.allowedAdditionalProperties, + }; + if (refs.target === "openApi3") { + return schema; } -} -function nodeDataJson(node) { - // if node.data implements Runnable - if (isRunnableInterface(node.data)) { + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && + def.keyType._def.checks?.length) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); return { - type: "runnable", - data: { - id: node.data.lc_id, - name: node.data.getName(), + ...schema, + propertyNames: keyType, + }; + } + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, }, }; } - else { + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && + def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && + def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); return { - type: "schema", - data: { ...zodToJsonSchema_zodToJsonSchema(node.data.schema), title: node.data.name }, + ...schema, + propertyNames: keyType, }; } + return schema; } -class Graph { - constructor(params) { - Object.defineProperty(this, "nodes", { - enumerable: true, - configurable: true, - writable: true, - value: {} - }); - Object.defineProperty(this, "edges", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - this.nodes = params?.nodes ?? this.nodes; - this.edges = params?.edges ?? this.edges; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/map.js + + +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") { + return parseRecordDef(def, refs); } - // Convert the graph to a JSON-serializable format. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - toJSON() { - const stableNodeIds = {}; - Object.values(this.nodes).forEach((node, i) => { - stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; - }); + const keys = parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"], + }) || {}; + const values = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"], + }) || {}; + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 + ? parsedTypes[0] === "string" + ? "string" + : "number" + : ["string", "number"], + enum: actualValues, + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/never.js +function parseNeverDef() { + return { + not: {}, + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/null.js +function parseNullDef(refs) { + return refs.target === "openApi3" + ? { + enum: ["null"], + nullable: true, + } + : { + type: "null", + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/union.js + +const primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null", +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in primitiveMappings && + (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); return { - nodes: Object.values(this.nodes).map((node) => ({ - id: stableNodeIds[node.id], - ...nodeDataJson(node), - })), - edges: this.edges.map((edge) => { - const item = { - source: stableNodeIds[edge.source], - target: stableNodeIds[edge.target], - }; - if (typeof edge.data !== "undefined") { - item.data = edge.data; - } - if (typeof edge.conditional !== "undefined") { - item.conditional = edge.conditional; - } - return item; - }), + type: types.length > 1 ? types : types[0], }; } - addNode(data, id, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - metadata) { - if (id !== undefined && this.nodes[id] !== undefined) { - throw new Error(`Node with id ${id} already exists`); + else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; } - const nodeId = id ?? v4(); - const node = { - id: nodeId, - data, - name: nodeDataStr(id, data), - metadata, - }; - this.nodes[nodeId] = node; - return node; - } - removeNode(node) { - // Remove the node from the nodes map - delete this.nodes[node.id]; - // Filter out edges connected to the node - this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); } - addEdge(source, target, data, conditional) { - if (this.nodes[source.id] === undefined) { - throw new Error(`Source node ${source.id} not in graph`); - } - if (this.nodes[target.id] === undefined) { - throw new Error(`Target node ${target.id} not in graph`); - } - const edge = { - source: source.id, - target: target.id, - data, - conditional, + else if (options.every((x) => x._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x) => [ + ...acc, + ...x._def.values.filter((x) => !acc.includes(x)), + ], []), }; - this.edges.push(edge); - return edge; - } - firstNode() { - return _firstNode(this); - } - lastNode() { - return _lastNode(this); } - /** - * Add all nodes and edges from another graph. - * Note this doesn't check for duplicates, nor does it connect the graphs. - */ - extend(graph, prefix = "") { - let finalPrefix = prefix; - const nodeIds = Object.values(graph.nodes).map((node) => node.id); - if (nodeIds.every(wrapper_validate)) { - finalPrefix = ""; - } - const prefixed = (id) => { - return finalPrefix ? `${finalPrefix}:${id}` : id; - }; - Object.entries(graph.nodes).forEach(([key, value]) => { - this.nodes[prefixed(key)] = { ...value, id: prefixed(key) }; - }); - const newEdges = graph.edges.map((edge) => { + return asAnyOf(def, refs); +} +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map + ? Array.from(def.options.values()) + : def.options) + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i}`], + })) + .filter((x) => !!x && + (!refs.strictUnions || + (typeof x === "object" && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js + + +function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { return { - ...edge, - source: prefixed(edge.source), - target: prefixed(edge.target), + type: primitiveMappings[def.innerType._def.typeName], + nullable: true, }; + } + return { + type: [ + primitiveMappings[def.innerType._def.typeName], + "null", + ], + }; + } + if (refs.target === "openApi3") { + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], }); - // Add all edges from the other graph - this.edges = [...this.edges, ...newEdges]; - const first = graph.firstNode(); - const last = graph.lastNode(); - return [ - first ? { id: prefixed(first.id), data: first.data } : undefined, - last ? { id: prefixed(last.id), data: last.data } : undefined, - ]; + if (base && "$ref" in base) + return { allOf: [base], nullable: true }; + return base && { ...base, nullable: true }; } - trimFirstNode() { - const firstNode = this.firstNode(); - if (firstNode && _firstNode(this, [firstNode.id])) { - this.removeNode(firstNode); + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"], + }); + return base && { anyOf: [base, { type: "null" }] }; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/number.js + +function parseNumberDef(def, refs) { + const res = { + type: "number", + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; } } - trimLastNode() { - const lastNode = this.lastNode(); - if (lastNode && _lastNode(this, [lastNode.id])) { - this.removeNode(lastNode); + return res; +} + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/object.js + + +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {}, + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === undefined || propDef._def === undefined) { + continue; } - } - /** - * Return a new graph with all nodes re-identified, - * using their unique, readable names where possible. - */ - reid() { - const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); - const nodeLabelCounts = new Map(); - Object.values(nodeLabels).forEach((label) => { - nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); - }); - const getNodeId = (nodeId) => { - const label = nodeLabels[nodeId]; - if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) { - return label; + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef instanceof ZodOptional) { + propDef = propDef._def.innerType; } - else { - return nodeId; + if (!propDef.isNullable()) { + propDef = propDef.nullable(); } - }; - return new Graph({ - nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [ - getNodeId(id), - { ...node, id: getNodeId(id) }, - ])), - edges: this.edges.map((edge) => ({ - ...edge, - source: getNodeId(edge.source), - target: getNodeId(edge.target), - })), + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName], }); + if (parsedDef === undefined) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required.push(propName); + } } - drawMermaid(params) { - const { withStyles, curveStyle, nodeColors = { - default: "fill:#f2f0ff,line-height:1.2", - first: "fill-opacity:0", - last: "fill:#bfb6fc", - }, wrapLabelNWords, } = params ?? {}; - const graph = this.reid(); - const firstNode = graph.firstNode(); - const lastNode = graph.lastNode(); - return drawMermaid(graph.nodes, graph.edges, { - firstNode: firstNode?.id, - lastNode: lastNode?.id, - withStyles, - curveStyle, - nodeColors, - wrapLabelNWords, - }); + if (required.length) { + result.required = required; } - async drawMermaidPng(params) { - const mermaidSyntax = this.drawMermaid(params); - return drawMermaidPng(mermaidSyntax, { - backgroundColor: params?.backgroundColor, + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== undefined) { + result.additionalProperties = additionalProperties; + } + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"], }); } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" + ? refs.allowedAdditionalProperties + : refs.rejectedAdditionalProperties; + } } -/** - * Find the single node that is not a target of any edge. - * Exclude nodes/sources with ids in the exclude list. - * If there is no such node, or there are multiple, return undefined. - * When drawing the graph, this node would be the origin. - */ -function _firstNode(graph, exclude = []) { - const targets = new Set(graph.edges - .filter((edge) => !exclude.includes(edge.source)) - .map((edge) => edge.target)); - const found = []; - for (const node of Object.values(graph.nodes)) { - if (!exclude.includes(node.id) && !targets.has(node.id)) { - found.push(node); - } +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } + catch { + return true; } - return found.length === 1 ? found[0] : undefined; } -/** - * Find the single node that is not a source of any edge. - * Exclude nodes/targets with ids in the exclude list. - * If there is no such node, or there are multiple, return undefined. - * When drawing the graph, this node would be the destination. - */ -function _lastNode(graph, exclude = []) { - const sources = new Set(graph.edges - .filter((edge) => !exclude.includes(edge.target)) - .map((edge) => edge.source)); - const found = []; - for (const node of Object.values(graph.nodes)) { - if (!exclude.includes(node.id) && !sources.has(node.id)) { - found.push(node); + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js + +const parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return parseDef(def.innerType._def, refs); + } + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"], + }); + return innerSchema + ? { + anyOf: [ + { + not: {}, + }, + innerSchema, + ], } + : {}; +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js + +const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return parseDef(def.in._def, refs); } - return found.length === 1 ? found[0] : undefined; + else if (refs.pipeStrategy === "output") { + return parseDef(def.out._def, refs); + } + const a = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"], + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"], + }); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/promise.js + +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/set.js -function convertToHttpEventStream(stream) { - const encoder = new TextEncoder(); - const finalStream = new ReadableStream({ - async start(controller) { - for await (const chunk of stream) { - controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); - } - controller.enqueue(encoder.encode("event: end\n\n")); - controller.close(); - }, + +function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"], }); - return IterableReadableStream.fromReadableStream(finalStream); + const schema = { + type: "array", + uniqueItems: true, + items, + }; + if (def.minSize) { + setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"], + }), + }; + } + else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} -function isIterableIterator(thing) { - return (typeof thing === "object" && - thing !== null && - typeof thing[Symbol.iterator] === "function" && - // avoid detecting array/set as iterator - typeof thing.next === "function"); +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js +function parseUndefinedDef() { + return { + not: {}, + }; } -const isIterator = (x) => x != null && - typeof x === "object" && - "next" in x && - typeof x.next === "function"; -function iter_isAsyncIterable(thing) { - return (typeof thing === "object" && - thing !== null && - typeof thing[Symbol.asyncIterator] === - "function"); + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js +function parseUnknownDef() { + return {}; } -function* consumeIteratorInContext(context, iter) { - while (true) { - const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); - if (done) { - break; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js + +const parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/selectParser.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +const selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(); + case ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + /* c8 ignore next */ + return ((_) => undefined)(typeName); + } +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parseDef.js + + +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; } - else { - yield value; + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== undefined) { + return seenSchema; } } + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive) + const jsonSchema = typeof jsonSchemaOrGetter === "function" + ? parseDef(jsonSchemaOrGetter(), refs) + : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; } -async function* consumeAsyncIterableInContext(context, iter) { - const iterator = iter[Symbol.asyncIterator](); - while (true) { - const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); - if (done) { - break; +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return {}; + } + return refs.$refStrategy === "seen" ? {} : undefined; } - else { - yield value; + } +}; +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; } } -} + return jsonSchema; +}; + +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js + + +const zodToJsonSchema_zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + const definitions = typeof options === "object" && options.definitions + ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ + ...acc, + [name]: parseDef(schema._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, true) ?? {}, + }), {}) + : undefined; + const name = typeof options === "string" + ? options + : options?.nameStrategy === "title" + ? undefined + : options?.name; + const main = parseDef(schema._def, name === undefined + ? refs + : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }, false) ?? {}; + const title = typeof options === "object" && + options.name !== undefined && + options.nameStrategy === "title" + ? options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + const combined = name === undefined + ? definitions + ? { + ...main, + [refs.definitionPath]: definitions, + } + : main + : { + $ref: [ + ...(refs.$refStrategy === "relative" ? [] : refs.basePath), + refs.definitionPath, + name, + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && + ("anyOf" in combined || + "oneOf" in combined || + "allOf" in combined || + ("type" in combined && Array.isArray(combined.type)))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; +}; -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/index.js @@ -98300,2221 +107716,2823 @@ async function* consumeAsyncIterableInContext(context, iter) { -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function base_coerceToDict(value, defaultKey) { - return value && - !Array.isArray(value) && - // eslint-disable-next-line no-instanceof/no-instanceof - !(value instanceof Date) && - typeof value === "object" - ? value - : { [defaultKey]: value }; + + + + + + + + + + + + + + + + + + + + + +/* harmony default export */ const dist_esm = ((/* unused pure expression or super */ null && (zodToJsonSchema))); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js +function deep_compare_strict_deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + const length = a.length; + if (length !== b.length) { + return false; + } + for (let i = 0; i < length; i++) { + if (!deep_compare_strict_deepCompareStrict(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeofa === 'object') { + if (!a || !b) { + return a === b; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const length = aKeys.length; + if (length !== bKeys.length) { + return false; + } + for (const k of aKeys) { + if (!deep_compare_strict_deepCompareStrict(a[k], b[k])) { + return false; + } + } + return true; + } + return a === b; } -/** - * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or - * transformed. - */ -class Runnable extends Serializable { - constructor() { - super(...arguments); - Object.defineProperty(this, "lc_runnable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js + +const schemaKeyword = { + additionalItems: true, + unevaluatedItems: true, + items: true, + contains: true, + additionalProperties: true, + unevaluatedProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; +const schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; +const schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true +}; +const ignoredKeyword = { + id: true, + $id: true, + $ref: true, + $schema: true, + $anchor: true, + $vocabulary: true, + $comment: true, + default: true, + enum: true, + const: true, + required: true, + type: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; +let initialBaseURI = typeof self !== 'undefined' && + self.location && + self.location.origin !== 'null' + ? + new URL(self.location.origin + self.location.pathname + location.search) + : new URL('https://github.com/cfworker'); +function dereference_dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { + if (schema && typeof schema === 'object' && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url = new URL(id, baseURI.href); + if (url.hash.length > 1) { + lookup[url.href] = schema; + } + else { + url.hash = ''; + if (basePointer === '') { + baseURI = url; + } + else { + dereference_dereference(schema, lookup, baseURI); + } + } + } } - getName(suffix) { - const name = - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.name ?? this.constructor.lc_name() ?? this.constructor.name; - return suffix ? `${name}${suffix}` : name; + else if (schema !== true && schema !== false) { + return lookup; } - /** - * Bind arguments to a Runnable, returning a new Runnable. - * @param kwargs - * @returns A new RunnableBinding that, when invoked, will apply the bound args. - */ - bind(kwargs) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ bound: this, kwargs, config: {} }); + const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); + if (lookup[schemaURI] !== undefined) { + throw new Error(`Duplicate schema URI "${schemaURI}".`); } - /** - * Return a new Runnable that maps a list of inputs to a list of outputs, - * by calling invoke() with each input. - */ - map() { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableEach({ bound: this }); + lookup[schemaURI] = schema; + if (schema === true || schema === false) { + return lookup; } - /** - * Add retry logic to an existing runnable. - * @param kwargs - * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. - */ - withRetry(fields) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields, + if (schema.__absolute_uri__ === undefined) { + Object.defineProperty(schema, '__absolute_uri__', { + enumerable: false, + value: schemaURI }); } - /** - * Bind config to a Runnable, returning a new Runnable. - * @param config New configuration parameters to attach to the new runnable. - * @returns A new RunnableBinding with a config matching what's passed. - */ - withConfig(config) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ - bound: this, - config, - kwargs: {}, + if (schema.$ref && schema.__absolute_ref__ === undefined) { + const url = new URL(schema.$ref, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_ref__', { + enumerable: false, + value: url.href }); } - /** - * Create a new runnable from the current one that will try invoking - * other passed fallback runnables if the initial invocation fails. - * @param fields.fallbacks Other runnables to call if the runnable errors. - * @returns A new RunnableWithFallbacks. - */ - withFallbacks(fields) { - const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableWithFallbacks({ - runnable: this, - fallbacks, + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { + const url = new URL(schema.$recursiveRef, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_recursive_ref__', { + enumerable: false, + value: url.href }); } - _getOptionsList(options, length = 0) { - if (Array.isArray(options) && options.length !== length) { - throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); + if (schema.$anchor) { + const url = new URL('#' + schema.$anchor, baseURI.href); + lookup[url.href] = schema; + } + for (let key in schema) { + if (ignoredKeyword[key]) { + continue; } - if (Array.isArray(options)) { - return options.map(ensureConfig); + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0; i < length; i++) { + dereference_dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + } + } } - if (length > 1 && !Array.isArray(options) && options.runId) { - console.warn("Provided runId will be used only for the first element of the batch."); - const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); - return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); + else if (schemaMapKeyword[key]) { + for (let subKey in subSchema) { + dereference_dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + } + } + else { + dereference_dereference(subSchema, lookup, baseURI, keyBase); } - return Array.from({ length }, () => ensureConfig(options)); } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const caller = new async_caller_AsyncCaller({ - maxConcurrency, - onFailedAttempt: (e) => { - throw e; - }, - }); - const batchCalls = inputs.map((input, i) => caller.call(async () => { - try { - const result = await this.invoke(input, configList[i]); - return result; - } - catch (e) { - if (batchOptions?.returnExceptions) { - return e; + return lookup; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +const FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/; +const FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i; +const FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i; +const FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i; +const EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split('@'); + if (!name || + !host || + rest.length !== 0 || + name.length > 64 || + host.length > 253) + return false; + if (name[0] === '.' || name.endsWith('.') || name.includes('..')) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || + !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host + .split('.') + .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); +}; +const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; +const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; +const DURATION = (input) => input.length > 1 && + input.length < 80 && + (/^P\d+([.,]\d+)?W$/.test(input) || + (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && + /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); +function bind(r) { + return r.test.bind(r); +} +const fullFormat = { + date: format_date, + time: format_time.bind(undefined, false), + 'date-time': date_time, + duration: DURATION, + uri, + 'uri-reference': bind(URIREF), + 'uri-template': bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex: regex, + uuid: bind(UUID), + 'json-pointer': bind(JSON_POINTER), + 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), + 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) +}; +const format_fastFormat = { + ...fullFormat, + date: bind(FASTDATE), + time: bind(FASTTIME), + 'date-time': bind(FASTDATETIME), + 'uri-reference': bind(FASTURIREFERENCE) +}; +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function format_date(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return (month >= 1 && + month <= 12 && + day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); +} +function format_time(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second = +matches[3]; + const timeZone = !!matches[5]; + return (((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone)); +} +const DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && format_date(dateTime[0]) && format_time(true, dateTime[1]); +} +const NOT_URI_FRAGMENT = /\/|:/; +const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +const Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, 'u'); + return true; + } + catch (e) { + return false; + } +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js +var OutputFormat; +(function (OutputFormat) { + OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; + OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; + OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; +})(OutputFormat || (OutputFormat = {})); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js + + + + + +function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { + if (schema === true) { + return { valid: true, errors: [] }; + } + if (schema === false) { + return { + valid: false, + errors: [ + { + instanceLocation, + keyword: 'false', + keywordLocation: instanceLocation, + error: 'False boolean schema.' } - throw e; - } - })); - return Promise.all(batchCalls); + ] + }; } - /** - * Default streaming implementation. - * Subclasses should override this method if they support streaming output. - * @param input - * @param options - */ - async *_streamIterator(input, options) { - yield this.invoke(input, options); + const rawInstanceType = typeof instance; + let instanceType; + switch (rawInstanceType) { + case 'boolean': + case 'number': + case 'string': + instanceType = rawInstanceType; + break; + case 'object': + if (instance === null) { + instanceType = 'null'; + } + else if (Array.isArray(instance)) { + instanceType = 'array'; + } + else { + instanceType = 'object'; + } + break; + default: + throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); } - /** - * Stream output in chunks. - * @param input - * @param options - * @returns A readable stream that is also an iterable. - */ - async stream(input, options) { - // Buffer the first streamed chunk to allow for initial errors - // to surface immediately. - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this._streamIterator(input, config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; + const errors = []; + if ($recursiveAnchor === true && recursiveAnchor === null) { + recursiveAnchor = schema; } - _separateRunnableConfigFromCallOptions(options) { - let runnableConfig; - if (options === undefined) { - runnableConfig = ensureConfig(options); - } - else { - runnableConfig = ensureConfig({ - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - runName: options.runName, - configurable: options.configurable, - recursionLimit: options.recursionLimit, - maxConcurrency: options.maxConcurrency, - runId: options.runId, - timeout: options.timeout, - signal: options.signal, - }); + if ($recursiveRef === '#') { + const refSchema = recursiveAnchor === null + ? lookup[__absolute_recursive_ref__] + : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$recursiveRef', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); } - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - delete callOptions.runName; - delete callOptions.configurable; - delete callOptions.recursionLimit; - delete callOptions.maxConcurrency; - delete callOptions.runId; - delete callOptions.timeout; - delete callOptions.signal; - return [runnableConfig, callOptions]; } - async _callWithConfig(func, input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, undefined, undefined, config?.runName ?? this.getName()); - delete config.runId; - let output; - try { - const promise = func.call(this, input, config, runManager); - output = await raceWithSignal(promise, options?.signal); - } - catch (e) { - await runManager?.handleChainError(e); - throw e; + if ($ref !== undefined) { + const uri = __absolute_ref__ || $ref; + const refSchema = lookup[uri]; + if (refSchema === undefined) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) { + message += ` Absolute URI "${__absolute_ref__}".`; + } + message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; + throw new Error(message); } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; - } - /** - * Internal method that handles batching and configuration for a runnable - * It takes a function, input values, and optional configuration, and - * returns a promise that resolves to the output values. - * @param func The function to be executed for each input value. - * @param input The input values to be processed. - * @param config Optional configuration for the function execution. - * @returns A promise that resolves to the output values. - */ - async _batchWithConfig(func, inputs, options, batchOptions) { - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName()); - delete optionsList[i].runId; - return handleStartRes; - })); - let outputs; - try { - const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); - outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$ref', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); } - catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; + if (draft === '4' || draft === '7') { + return { valid: errors.length === 0, errors }; } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); - return outputs; } - /** - * Helper method to transform an Iterator of Input values into an Iterator of - * Output values, with callbacks. - * Use this to implement `stream()` or `transform()` in Runnable subclasses. - */ - async *_transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (finalInputSupported) { - if (finalInput === undefined) { - finalInput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalInput = concat(finalInput, chunk); - } - catch { - finalInput = undefined; - finalInputSupported = false; - } - } - } - yield chunk; - } - } - let runManager; - try { - const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), options?.signal, config); - delete config.runId; - runManager = pipe.setup; - const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); - let iterator = pipe.output; - if (streamEventsHandler !== undefined && runManager !== undefined) { - iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); - } - const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); - if (streamLogHandler !== undefined && runManager !== undefined) { - iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); - } - for await (const chunk of iterator) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } + if (Array.isArray($type)) { + let length = $type.length; + let valid = false; + for (let i = 0; i < length; i++) { + if (instanceType === $type[i] || + ($type[i] === 'integer' && + instanceType === 'number' && + instance % 1 === 0 && + instance === instance)) { + valid = true; + break; } } - catch (e) { - await runManager?.handleChainError(e, undefined, undefined, undefined, { - inputs: base_coerceToDict(finalInput, "input"), + if (!valid) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` }); - throw e; } - await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: base_coerceToDict(finalInput, "input") }); } - getGraph(_) { - const graph = new Graph(); - // TODO: Add input schema for runnables - const inputNode = graph.addNode({ - name: `${this.getName()}Input`, - schema: z.any(), - }); - const runnableNode = graph.addNode(this); - // TODO: Add output schemas for runnables - const outputNode = graph.addNode({ - name: `${this.getName()}Output`, - schema: z.any(), - }); - graph.addEdge(inputNode, runnableNode); - graph.addEdge(runnableNode, outputNode); - return graph; + else if ($type === 'integer') { + if (instanceType !== 'number' || instance % 1 || instance !== instance) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } } - /** - * Create a new runnable sequence that runs each individual runnable in series, - * piping the output of one runnable into another runnable or runnable-like. - * @param coerceable A runnable, function, or object whose values are functions or runnables. - * @returns A new runnable sequence. - */ - pipe(coerceable) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableSequence({ - first: this, - last: _coerceToRunnable(coerceable), + else if ($type !== undefined && instanceType !== $type) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` }); } - /** - * Pick keys from the dict output of this runnable. Returns a new runnable. - */ - pick(keys) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return this.pipe(new RunnablePick(keys)); - } - /** - * Assigns new fields to the dict output of this runnable. Returns a new runnable. - */ - assign(mapping) { - return this.pipe( - // eslint-disable-next-line @typescript-eslint/no-use-before-define - new RunnableAssign( - // eslint-disable-next-line @typescript-eslint/no-use-before-define - new RunnableMap({ steps: mapping }))); - } - /** - * Default implementation of transform, which buffers input and then calls stream. - * Subclasses should override this method if they can start producing output while - * input is still being generated. - * @param generator - * @param options - */ - async *transform(generator, options) { - let finalChunk; - for await (const chunk of generator) { - if (finalChunk === undefined) { - finalChunk = chunk; + if ($const !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!deepCompareStrict(instance, $const)) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); } - else { - // Make a best effort to gather, for any type that supports concat. - // This method should throw an error if gathering fails. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalChunk = concat(finalChunk, chunk); + } + else if (instance !== $const) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + if ($enum !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!$enum.some(value => deepCompareStrict(instance, value))) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); } } - yield* this._streamIterator(finalChunk, ensureConfig(options)); + else if (!$enum.some(value => instance === value)) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } } - /** - * Stream all output from a runnable, as reported to the callback system. - * This includes all inner runs of LLMs, Retrievers, Tools, etc. - * Output is streamed as Log objects, which include a list of - * jsonpatch ops that describe how the state of the run has changed in each - * step, and the final state of the run. - * The jsonpatch ops can be applied in order to construct state. - * @param input - * @param options - * @param streamOptions - */ - async *streamLog(input, options, streamOptions) { - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "original", - }); - const config = ensureConfig(options); - yield* this._streamLog(input, logStreamCallbackHandler, config); + if ($not !== undefined) { + const keywordLocation = `${schemaLocation}/not`; + const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); + if (result.valid) { + errors.push({ + instanceLocation, + keyword: 'not', + keywordLocation, + error: 'Instance matched "not" schema.' + }); + } } - async *_streamLog(input, logStreamCallbackHandler, config) { - const { callbacks } = config; - if (callbacks === undefined) { - // eslint-disable-next-line no-param-reassign - config.callbacks = [logStreamCallbackHandler]; + let subEvaluateds = []; + if ($anyOf !== undefined) { + const keywordLocation = `${schemaLocation}/anyOf`; + const errorsLength = errors.length; + let anyValid = false; + for (let i = 0; i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + anyValid = anyValid || result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } } - else if (Array.isArray(callbacks)) { - // eslint-disable-next-line no-param-reassign - config.callbacks = callbacks.concat([logStreamCallbackHandler]); + if (anyValid) { + errors.length = errorsLength; } else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(logStreamCallbackHandler, true); - // eslint-disable-next-line no-param-reassign - config.callbacks = copiedCallbacks; + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'anyOf', + keywordLocation, + error: 'Instance does not match any subschemas.' + }); } - const runnableStreamPromise = this.stream(input, config); - async function consumeRunnableStream() { - try { - const runnableStream = await runnableStreamPromise; - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ - ops: [ - { - op: "add", - path: "/streamed_output/-", - value: chunk, - }, - ], - }); - await logStreamCallbackHandler.writer.write(patch); - } - } - finally { - await logStreamCallbackHandler.writer.close(); + } + if ($allOf !== undefined) { + const keywordLocation = `${schemaLocation}/allOf`; + const errorsLength = errors.length; + let allValid = true; + for (let i = 0; i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + allValid = allValid && result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); } } - const runnableStreamConsumePromise = consumeRunnableStream(); - try { - for await (const log of logStreamCallbackHandler) { - yield log; - } + if (allValid) { + errors.length = errorsLength; } - finally { - await runnableStreamConsumePromise; + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'allOf', + keywordLocation, + error: `Instance does not match every subschema.` + }); } } - streamEvents(input, options, streamOptions) { - let stream; - if (options.version === "v1") { - stream = this._streamEventsV1(input, options, streamOptions); - } - else if (options.version === "v2") { - stream = this._streamEventsV2(input, options, streamOptions); + if ($oneOf !== undefined) { + const keywordLocation = `${schemaLocation}/oneOf`; + const errorsLength = errors.length; + const matches = $oneOf.filter((subSchema, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + return result.valid; + }).length; + if (matches === 1) { + errors.length = errorsLength; } else { - throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'oneOf', + keywordLocation, + error: `Instance does not match exactly one subschema (${matches} matches).` + }); } - if (options.encoding === "text/event-stream") { - return convertToHttpEventStream(stream); + } + if (instanceType === 'object' || instanceType === 'array') { + Object.assign(evaluated, ...subEvaluateds); + } + if ($if !== undefined) { + const keywordLocation = `${schemaLocation}/if`; + const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; + if (conditionResult) { + if ($then !== undefined) { + const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); + if (!thenResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "then" schema.` + }, ...thenResult.errors); + } + } } - else { - return IterableReadableStream.fromAsyncGenerator(stream); + else if ($else !== undefined) { + const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); + if (!elseResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "else" schema.` + }, ...elseResult.errors); + } } } - async *_streamEventsV2(input, options, streamOptions) { - const eventStreamer = new EventStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - }); - const config = ensureConfig(options); - const runId = config.runId ?? v4(); - config.runId = runId; - const callbacks = config.callbacks; - if (callbacks === undefined) { - config.callbacks = [eventStreamer]; + if (instanceType === 'object') { + if ($required !== undefined) { + for (const key of $required) { + if (!(key in instance)) { + errors.push({ + instanceLocation, + keyword: 'required', + keywordLocation: `${schemaLocation}/required`, + error: `Instance does not have required property "${key}".` + }); + } + } + } + const keys = Object.keys(instance); + if ($minProperties !== undefined && keys.length < $minProperties) { + errors.push({ + instanceLocation, + keyword: 'minProperties', + keywordLocation: `${schemaLocation}/minProperties`, + error: `Instance does not have at least ${$minProperties} properties.` + }); + } + if ($maxProperties !== undefined && keys.length > $maxProperties) { + errors.push({ + instanceLocation, + keyword: 'maxProperties', + keywordLocation: `${schemaLocation}/maxProperties`, + error: `Instance does not have at least ${$maxProperties} properties.` + }); } - else if (Array.isArray(callbacks)) { - config.callbacks = callbacks.concat(eventStreamer); + if ($propertyNames !== undefined) { + const keywordLocation = `${schemaLocation}/propertyNames`; + for (const key in instance) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'propertyNames', + keywordLocation, + error: `Property name "${key}" does not match schema.` + }, ...result.errors); + } + } } - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(eventStreamer, true); - // eslint-disable-next-line no-param-reassign - config.callbacks = copiedCallbacks; + if ($dependentRequired !== undefined) { + const keywordLocation = `${schemaLocation}/dependantRequired`; + for (const key in $dependentRequired) { + if (key in instance) { + const required = $dependentRequired[key]; + for (const dependantKey of required) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependentRequired', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + } } - const abortController = new AbortController(); - // Call the runnable in streaming mode, - // add each chunk to the output stream - const outerThis = this; - async function consumeRunnableStream() { - try { - let signal; - if (options?.signal) { - if ("any" in AbortSignal) { - // Use native AbortSignal.any() if available (Node 19+) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - signal = AbortSignal.any([ - abortController.signal, - options.signal, - ]); + if ($dependentSchemas !== undefined) { + for (const key in $dependentSchemas) { + const keywordLocation = `${schemaLocation}/dependentSchemas`; + if (key in instance) { + const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependentSchemas', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + if ($dependencies !== undefined) { + const keywordLocation = `${schemaLocation}/dependencies`; + for (const key in $dependencies) { + if (key in instance) { + const propsOrSchema = $dependencies[key]; + if (Array.isArray(propsOrSchema)) { + for (const dependantKey of propsOrSchema) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } } else { - // Fallback for Node 18 and below - just use the provided signal - signal = options.signal; - // Ensure we still abort our controller when the parent signal aborts - options.signal.addEventListener("abort", () => { - abortController.abort(); - }, { once: true }); + const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } } } - else { - signal = abortController.signal; + } + } + const thisEvaluated = Object.create(null); + let stop = false; + if ($properties !== undefined) { + const keywordLocation = `${schemaLocation}/properties`; + for (const key in $properties) { + if (!(key in instance)) { + continue; } - const runnableStream = await outerThis.stream(input, { - ...config, - signal, - }); - const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - for await (const _ of tappedStream) { - // Just iterate so that the callback handler picks up events - if (abortController.signal.aborted) + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'properties', + keywordLocation, + error: `Property "${key}" does not match schema.` + }, ...result.errors); + if (stop) break; } } - finally { - await eventStreamer.finish(); + } + if (!stop && $patternProperties !== undefined) { + const keywordLocation = `${schemaLocation}/patternProperties`; + for (const pattern in $patternProperties) { + const regex = new RegExp(pattern, 'u'); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex.test(key)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'patternProperties', + keywordLocation, + error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` + }, ...result.errors); + } + } } } - const runnableStreamConsumePromise = consumeRunnableStream(); - let firstEventSent = false; - let firstEventRunId; - try { - for await (const event of eventStreamer) { - // This is a work-around an issue where the inputs into the - // chain are not available until the entire input is consumed. - // As a temporary solution, we'll modify the input to be the input - // that was passed into the chain. - if (!firstEventSent) { - event.data.input = input; - firstEventSent = true; - firstEventRunId = event.run_id; - yield event; + if (!stop && $additionalProperties !== undefined) { + const keywordLocation = `${schemaLocation}/additionalProperties`; + for (const key in instance) { + if (thisEvaluated[key]) { continue; } - if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { - // If it's the end event corresponding to the root runnable - // we dont include the input in the event since it's guaranteed - // to be included in the first event. - if (event.data?.input) { - delete event.data.input; - } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalProperties', + keywordLocation, + error: `Property "${key}" does not match additional properties schema.` + }, ...result.errors); } - yield event; } } - finally { - abortController.abort(); - await runnableStreamConsumePromise; + else if (!stop && $unevaluatedProperties !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedProperties`; + for (const key in instance) { + if (!evaluated[key]) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + errors.push({ + instanceLocation, + keyword: 'unevaluatedProperties', + keywordLocation, + error: `Property "${key}" does not match unevaluated properties schema.` + }, ...result.errors); + } + } + } } } - async *_streamEventsV1(input, options, streamOptions) { - let runLog; - let hasEncounteredStartEvent = false; - const config = ensureConfig(options); - const rootTags = config.tags ?? []; - const rootMetadata = config.metadata ?? {}; - const rootName = config.runName ?? this.getName(); - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "streaming_events", - }); - const rootEventFilter = new _RootEventFilter({ - ...streamOptions, - }); - const logStream = this._streamLog(input, logStreamCallbackHandler, config); - for await (const log of logStream) { - if (!runLog) { - runLog = RunLog.fromRunLogPatch(log); + else if (instanceType === 'array') { + if ($maxItems !== undefined && instance.length > $maxItems) { + errors.push({ + instanceLocation, + keyword: 'maxItems', + keywordLocation: `${schemaLocation}/maxItems`, + error: `Array has too many items (${instance.length} > ${$maxItems}).` + }); + } + if ($minItems !== undefined && instance.length < $minItems) { + errors.push({ + instanceLocation, + keyword: 'minItems', + keywordLocation: `${schemaLocation}/minItems`, + error: `Array has too few items (${instance.length} < ${$minItems}).` + }); + } + const length = instance.length; + let i = 0; + let stop = false; + if ($prefixItems !== undefined) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (; i < length2; i++) { + const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'prefixItems', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } } - else { - runLog = runLog.concat(log); + } + if ($items !== undefined) { + const keywordLocation = `${schemaLocation}/items`; + if (Array.isArray($items)) { + const length2 = Math.min($items.length, length); + for (; i < length2; i++) { + const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } - if (runLog.state === undefined) { - throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + else { + for (; i < length; i++) { + const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } } - // Yield the start event for the root runnable if it hasn't been seen. - // The root run is never filtered out - if (!hasEncounteredStartEvent) { - hasEncounteredStartEvent = true; - const state = { ...runLog.state }; - const event = { - run_id: state.id, - event: `on_${state.type}_start`, - name: rootName, - tags: rootTags, - metadata: rootMetadata, - data: { - input, - }, - }; - if (rootEventFilter.includeEvent(event, state.type)) { - yield event; + if (!stop && $additionalItems !== undefined) { + const keywordLocation = `${schemaLocation}/additionalItems`; + for (; i < length; i++) { + const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalItems', + keywordLocation, + error: `Items did not match additional items schema.` + }, ...result.errors); + } } } - const paths = log.ops - .filter((op) => op.path.startsWith("/logs/")) - .map((op) => op.path.split("/")[2]); - const dedupedPaths = [...new Set(paths)]; - for (const path of dedupedPaths) { - let eventType; - let data = {}; - const logEntry = runLog.state.logs[path]; - if (logEntry.end_time === undefined) { - if (logEntry.streamed_output.length > 0) { - eventType = "stream"; + } + if ($contains !== undefined) { + if (length === 0 && $minContains === undefined) { + errors.push({ + instanceLocation, + keyword: 'contains', + keywordLocation: `${schemaLocation}/contains`, + error: `Array is empty. It must contain at least one item matching the schema.` + }); + } + else if ($minContains !== undefined && length < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array has less items (${length}) than minContains (${$minContains}).` + }); + } + else { + const keywordLocation = `${schemaLocation}/contains`; + const errorsLength = errors.length; + let contained = 0; + for (let j = 0; j < length; j++) { + const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = true; + contained++; } else { - eventType = "start"; + errors.push(...result.errors); } } - else { - eventType = "end"; + if (contained >= ($minContains || 0)) { + errors.length = errorsLength; } - if (eventType === "start") { - // Include the inputs with the start event if they are available. - // Usually they will NOT be available for components that operate - // on streams, since those components stream the input and - // don't know its final value until the end of the stream. - if (logEntry.inputs !== undefined) { - data.input = logEntry.inputs; - } + if ($minContains === undefined && + $maxContains === undefined && + contained === 0) { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'contains', + keywordLocation, + error: `Array does not contain item matching schema.` + }); } - else if (eventType === "end") { - if (logEntry.inputs !== undefined) { - data.input = logEntry.inputs; - } - data.output = logEntry.final_output; + else if ($minContains !== undefined && contained < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` + }); } - else if (eventType === "stream") { - const chunkCount = logEntry.streamed_output.length; - if (chunkCount !== 1) { - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); + else if ($maxContains !== undefined && contained > $maxContains) { + errors.push({ + instanceLocation, + keyword: 'maxContains', + keywordLocation: `${schemaLocation}/maxContains`, + error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` + }); + } + } + } + if (!stop && $unevaluatedItems !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedItems`; + for (i; i < length; i++) { + if (evaluated[i]) { + continue; + } + const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'unevaluatedItems', + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); + } + } + } + if ($uniqueItems) { + for (let j = 0; j < length; j++) { + const a = instance[j]; + const ao = typeof a === 'object' && a !== null; + for (let k = 0; k < length; k++) { + if (j === k) { + continue; + } + const b = instance[k]; + const bo = typeof b === 'object' && b !== null; + if (a === b || (ao && bo && deepCompareStrict(a, b))) { + errors.push({ + instanceLocation, + keyword: 'uniqueItems', + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = Number.MAX_SAFE_INTEGER; } - data = { chunk: logEntry.streamed_output[0] }; - // Clean up the stream, we don't need it anymore. - // And this avoids duplicates as well! - logEntry.streamed_output = []; } - yield { - event: `on_${logEntry.type}_${eventType}`, - name: logEntry.name, - run_id: logEntry.id, - tags: logEntry.tags, - metadata: logEntry.metadata, - data, - }; } - // Finally, we take care of the streaming output from the root chain - // if there is any. - const { state } = runLog; - if (state.streamed_output.length > 0) { - const chunkCount = state.streamed_output.length; - if (chunkCount !== 1) { - throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`); - } - const data = { chunk: state.streamed_output[0] }; - // Clean up the stream, we don't need it anymore. - state.streamed_output = []; - const event = { - event: `on_${state.type}_stream`, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - name: rootName, - data, - }; - if (rootEventFilter.includeEvent(event, state.type)) { - yield event; - } + } + } + else if (instanceType === 'number') { + if (draft === '4') { + if ($minimum !== undefined && + (($exclusiveMinimum === true && instance <= $minimum) || + instance < $minimum)) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` + }); + } + if ($maximum !== undefined && + (($exclusiveMaximum === true && instance >= $maximum) || + instance > $maximum)) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` + }); + } + } + else { + if ($minimum !== undefined && instance < $minimum) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$minimum}.` + }); + } + if ($maximum !== undefined && instance > $maximum) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$maximum}.` + }); + } + if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMinimum', + keywordLocation: `${schemaLocation}/exclusiveMinimum`, + error: `${instance} is less than ${$exclusiveMinimum}.` + }); + } + if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMaximum', + keywordLocation: `${schemaLocation}/exclusiveMaximum`, + error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` + }); } } - const state = runLog?.state; - if (state !== undefined) { - // Finally, yield the end event for the root runnable. - const event = { - event: `on_${state.type}_end`, - name: rootName, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - data: { - output: state.final_output, - }, - }; - if (rootEventFilter.includeEvent(event, state.type)) - yield event; + if ($multipleOf !== undefined) { + const remainder = instance % $multipleOf; + if (Math.abs(0 - remainder) >= 1.1920929e-7 && + Math.abs($multipleOf - remainder) >= 1.1920929e-7) { + errors.push({ + instanceLocation, + keyword: 'multipleOf', + keywordLocation: `${schemaLocation}/multipleOf`, + error: `${instance} is not a multiple of ${$multipleOf}.` + }); + } } } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnable(thing) { - return isRunnableInterface(thing); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError, }) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - return new RunnableBinding({ - bound: this, - config: {}, - configFactories: [ - (config) => ({ - callbacks: [ - new RootListenersTracer({ - config, - onStart, - onEnd, - onError, - }), - ], - }), - ], - }); - } - /** - * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` - * which contains the runnable, name, description and schema. - * - * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. - * - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ - asTool(fields) { - return convertRunnableToTool(this, fields); + else if (instanceType === 'string') { + const length = $minLength === undefined && $maxLength === undefined + ? 0 + : ucs2length(instance); + if ($minLength !== undefined && length < $minLength) { + errors.push({ + instanceLocation, + keyword: 'minLength', + keywordLocation: `${schemaLocation}/minLength`, + error: `String is too short (${length} < ${$minLength}).` + }); + } + if ($maxLength !== undefined && length > $maxLength) { + errors.push({ + instanceLocation, + keyword: 'maxLength', + keywordLocation: `${schemaLocation}/maxLength`, + error: `String is too long (${length} > ${$maxLength}).` + }); + } + if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { + errors.push({ + instanceLocation, + keyword: 'pattern', + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); + } + if ($format !== undefined && + fastFormat[$format] && + !fastFormat[$format](instance)) { + errors.push({ + instanceLocation, + keyword: 'format', + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` + }); + } } + return { valid: errors.length === 0, errors }; } -/** - * A runnable that delegates calls to another runnable with a set of kwargs. - * @example - * ```typescript - * import { - * type RunnableConfig, - * RunnableLambda, - * } from "@langchain/core/runnables"; - * - * const enhanceProfile = ( - * profile: Record, - * config?: RunnableConfig - * ) => { - * if (config?.configurable?.role) { - * return { ...profile, role: config.configurable.role }; - * } - * return profile; - * }; - * - * const runnable = RunnableLambda.from(enhanceProfile); - * - * // Bind configuration to the runnable to set the user's role dynamically - * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } }); - * const userRunnable = runnable.bind({ configurable: { role: "User" } }); - * - * const result1 = await adminRunnable.invoke({ - * name: "Alice", - * email: "alice@example.com" - * }); - * - * // { name: "Alice", email: "alice@example.com", role: "Admin" } - * - * const result2 = await userRunnable.invoke({ - * name: "Bob", - * email: "bob@example.com" - * }); - * - * // { name: "Bob", email: "bob@example.com", role: "User" } - * ``` - */ -class RunnableBinding extends Runnable { - static lc_name() { - return "RunnableBinding"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "config", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "kwargs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "configFactories", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - this.configFactories = fields.configFactories; - } - getName(suffix) { - return this.bound.getName(suffix); - } - async _mergeConfig(...options) { - const config = mergeConfigs(this.config, ...options); - return mergeConfigs(config, ...(this.configFactories - ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) - : [])); - } - bind(kwargs) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new this.constructor({ - bound: this.bound, - kwargs: { ...this.kwargs, ...kwargs }, - config: this.config, - }); - } - withConfig(config) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { ...this.config, ...config }, - }); - } - withRetry(fields) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new this.constructor({ - bound: this.bound.withRetry(fields), - kwargs: this.kwargs, - config: this.config, - }); - } - async invoke(input, options) { - return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) - ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) - : await this._mergeConfig(ensureConfig(options), this.kwargs); - return this.bound.batch(inputs, mergedOptions, batchOptions); - } - async *_streamIterator(input, options) { - yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async stream(input, options) { - return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async *transform(generator, options) { - yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - streamEvents(input, options, streamOptions) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - const outerThis = this; - const generator = async function* () { - yield* outerThis.bound.streamEvents(input, { - ...(await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs)), - version: options.version, - }, streamOptions); - }; - return IterableReadableStream.fromAsyncGenerator(generator()); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js + + +class Validator { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = '2019-09', shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); } - static isRunnableBinding( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - thing - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ) { - return thing.bound && Runnable.isRunnable(thing.bound); + validate(instance) { + return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError, }) { - return new RunnableBinding({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - configFactories: [ - (config) => ({ - callbacks: [ - new RootListenersTracer({ - config, - onStart, - onEnd, - onError, - }), - ], - }), - ], - }); + addSchema(schema, id) { + if (id) { + schema = { ...schema, $id: id }; + } + dereference(schema, this.lookup); } } -/** - * A runnable that delegates calls to another runnable - * with each element of the input sequence. - * @example - * ```typescript - * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; - * - * const toUpperCase = (input: string): string => input.toUpperCase(); - * const addGreeting = (input: string): string => `Hello, ${input}!`; - * - * const upperCaseLambda = RunnableLambda.from(toUpperCase); - * const greetingLambda = RunnableLambda.from(addGreeting); - * - * const chain = new RunnableEach({ - * bound: upperCaseLambda.pipe(greetingLambda), - * }); - * - * const result = await chain.invoke(["alice", "bob", "carol"]) - * - * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] - * ``` - */ -class RunnableEach extends Runnable { - static lc_name() { - return "RunnableEach"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "bound", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.bound = fields.bound; - } - /** - * Binds the runnable with the specified arguments. - * @param kwargs The arguments to bind the runnable with. - * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. - */ - bind(kwargs) { - return new RunnableEach({ - bound: this.bound.bind(kwargs), - }); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/zod.js + +function isZodSchemaV4(schema) { + if (typeof schema !== "object" || schema === null) { + return false; } - /** - * Invokes the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(inputs, config) { - return this._callWithConfig(this._invoke.bind(this), inputs, config); + const obj = schema; + if (!("_zod" in obj)) { + return false; } - /** - * A helper method that is used to invoke the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async _invoke(inputs, config, runManager) { - return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); + const zod = obj._zod; + return (typeof zod === "object" && + zod !== null && + "def" in zod); +} +function isZodSchemaV3(schema) { + if (typeof schema !== "object" || schema === null) { + return false; } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError, }) { - return new RunnableEach({ - bound: this.bound.withListeners({ onStart, onEnd, onError }), - }); + const obj = schema; + if (!("_def" in obj) || "_zod" in obj) { + return false; } + const def = obj._def; + return (typeof def === "object" && + def != null && + "typeName" in def); } -/** - * Base class for runnables that can be retried a - * specified number of times. - * @example - * ```typescript - * import { - * RunnableLambda, - * RunnableRetry, - * } from "@langchain/core/runnables"; - * - * // Simulate an API call that fails - * const simulateApiCall = (input: string): string => { - * console.log(`Attempting API call with input: ${input}`); - * throw new Error("API call failed due to network issue"); - * }; - * - * const apiCallLambda = RunnableLambda.from(simulateApiCall); - * - * // Apply retry logic using the .withRetry() method - * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); - * - * // Alternatively, create a RunnableRetry instance manually - * const manualRetry = new RunnableRetry({ - * bound: apiCallLambda, - * maxAttemptNumber: 3, - * config: {}, - * }); - * - * // Example invocation using the .withRetry() method - * const res = await apiCallWithRetry - * .invoke("Request 1") - * .catch((error) => { - * console.error("Failed after multiple retries:", error.message); - * }); +/** Backward compatible isZodSchema for Zod 3 */ +function isZodSchema(schema) { + if (isZodSchemaV4(schema)) { + console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); + } + return isZodSchemaV3(schema); +} +/** + * Given either a Zod schema, or plain object, determine if the input is a Zod schema. * - * // Example invocation using the manual retry instance - * const res2 = await manualRetry - * .invoke("Request 2") - * .catch((error) => { - * console.error("Failed after multiple retries:", error.message); - * }); - * ``` + * @param {unknown} input + * @returns {boolean} Whether or not the provided input is a Zod schema. */ -class RunnableRetry extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "maxAttemptNumber", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "onFailedAttempt", { - enumerable: true, - configurable: true, - writable: true, - value: () => { } - }); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; +function isInteropZodSchema(input) { + if (!input) { + return false; } - _patchConfigForRetry(attempt, config, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; - return patchConfig(config, { callbacks: runManager?.getChild(tag) }); + if (typeof input !== "object") { + return false; } - async _invoke(input, config, runManager) { - return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onFailedAttempt: (error) => this.onFailedAttempt(error, input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true, - }); + if (Array.isArray(input)) { + return false; } - /** - * Method that invokes the runnable with the specified input, run manager, - * and config. It handles the retry logic by catching any errors and - * recursively invoking itself with the updated config for the next retry - * attempt. - * @param input The input for the runnable. - * @param runManager The run manager for the runnable. - * @param config The config for the runnable. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(input, config) { - return this._callWithConfig(this._invoke.bind(this), input, config); + if (isZodSchemaV4(input) || + isZodSchemaV3(input)) { + return true; } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; + return false; +} +/** + * Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. + * This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {Promise>} A promise that resolves to a safe parse result object. + * @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. + */ +async function interopSafeParseAsync(schema, input) { + if (isZodSchemaV4(schema)) { try { - await p_retry(async (attemptNumber) => { - const remainingIndexes = inputs - .map((_, i) => i) - .filter((i) => resultsMap[i.toString()] === undefined || - // eslint-disable-next-line no-instanceof/no-instanceof - resultsMap[i.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i) => inputs[i]); - const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true, - }); - let firstException; - for (let i = 0; i < results.length; i += 1) { - const result = results[i]; - const resultMapIndex = remainingIndexes[i]; - // eslint-disable-next-line no-instanceof/no-instanceof - if (result instanceof Error) { - if (firstException === undefined) { - firstException = result; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - firstException.input = remainingInputs[i]; - } - } - resultsMap[resultMapIndex.toString()] = result; - } - if (firstException) { - throw firstException; - } - return results; - }, { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true, - }); + const data = await parse_parseAsync(schema, input); + return { + success: true, + data, + }; } - catch (e) { - if (batchOptions?.returnExceptions !== true) { - throw e; - } + catch (error) { + return { + success: false, + error: error, + }; } - return Object.keys(resultsMap) - .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) - .map((key) => resultsMap[parseInt(key, 10)]); } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); + if (isZodSchemaV3(schema)) { + return schema.safeParse(input); } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); } /** - * A sequence of runnables, where the output of each is the input of the next. - * @example - * ```typescript - * const promptTemplate = PromptTemplate.fromTemplate( - * "Tell me a joke about {topic}", - * ); - * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]); - * const result = await chain.invoke({ topic: "bears" }); - * ``` + * Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. + * Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {Promise} A promise that resolves to the parsed value. + * @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. */ -class RunnableSequence extends Runnable { - static lc_name() { - return "RunnableSequence"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "first", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "middle", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "last", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "omitSequenceTags", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - this.name = fields.name; - this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; +async function interopParseAsync(schema, input) { + if (isZodSchemaV4(schema)) { + return parse_parse(schema, input); } - get steps() { - return [this.first, ...this.middle, this.last]; + if (isZodSchemaV3(schema)) { + return schema.parse(input); } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config?.runName); - delete config.runId; - let nextStepInput = input; - let finalOutput; + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object + * indicating success or failure. This function is compatible with both Zod v3 and v4 schemas. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {InteropZodSafeParseResult} An object with either the parsed data (on success) + * or the error (on failure). + * @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. + */ +function interopSafeParse(schema, input) { + if (isZodSchemaV4(schema)) { try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0; i < initialSteps.length; i += 1) { - const step = initialSteps[i]; - const promise = step.invoke(nextStepInput, patchConfig(config, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), - })); - nextStepInput = await raceWithSignal(promise, options?.signal); - } - // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here - if (options?.signal?.aborted) { - throw new Error("Aborted"); - } - finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`), - })); + const data = parse(schema, input); + return { + success: true, + data, + }; } - catch (e) { - await runManager?.handleChainError(e); - throw e; + catch (error) { + return { + success: false, + error: error, + }; } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); - return finalOutput; } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let nextStepInputs = inputs; - try { - for (let i = 0; i < this.steps.length; i += 1) { - const step = this.steps[i]; - const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { - const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`); - return patchConfig(configList[j], { callbacks: childRunManager }); - }), batchOptions); - nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); - } - } - catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); - return nextStepInputs; + if (isZodSchemaV3(schema)) { + return schema.safeParse(input); } - async *_streamIterator(input, options) { - const callbackManager_ = await getCallbackManagerForConfig(options); - const { runId, ...otherOptions } = options ?? {}; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName); - const steps = [this.first, ...this.middle, this.last]; - let concatSupported = true; - let finalOutput; - async function* inputGenerator() { - yield input; + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. + * Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. + * + * @template T - The expected output type of the schema. + * @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. + * @param {unknown} input - The input value to parse. + * @returns {T} The parsed value. + * @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. + */ +function interopParse(schema, input) { + if (isZodSchemaV4(schema)) { + return parse(schema, input); + } + if (isZodSchemaV3(schema)) { + return schema.parse(input); + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** + * Retrieves the description from a schema definition (v3, v4, or plain object), if available. + * + * @param {unknown} schema - The schema to extract the description from. + * @returns {string | undefined} The description of the schema, or undefined if not present. + */ +function getSchemaDescription(schema) { + if (isZodSchemaV4(schema)) { + return globalRegistry.get(schema)?.description; + } + if (isZodSchemaV3(schema)) { + return schema.description; + } + if ("description" in schema && typeof schema.description === "string") { + return schema.description; + } + return undefined; +} +/** + * Determines if the provided Zod schema is "shapeless". + * A shapeless schema is one that does not define any object shape, + * such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. + * For ZodObject, it must have no shape keys to be considered shapeless. + * ZodRecord schemas are considered shapeless since they define dynamic + * key-value mappings without fixed keys. + * + * @param schema The Zod schema to check. + * @returns {boolean} True if the schema is shapeless, false otherwise. + */ +function isShapelessZodSchema(schema) { + if (!isInteropZodSchema(schema)) { + return false; + } + // Check for v3 schemas + if (isZodSchemaV3(schema)) { + // @ts-expect-error - zod v3 types are not compatible with zod v4 types + const def = schema._def; + // ZodObject is only shaped if it has actual shape keys + if (def.typeName === "ZodObject") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + // ZodRecord is shapeless (dynamic key-value mapping) + if (def.typeName === "ZodRecord") { + return true; } - try { - let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`), - })); - for (let i = 1; i < steps.length; i += 1) { - const step = steps[i]; - finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { - callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), - })); - } - for await (const chunk of finalGenerator) { - options?.signal?.throwIfAborted(); - yield chunk; - if (concatSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = undefined; - concatSupported = false; - } - } - } - } + } + // Check for v4 schemas + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + // Object type is only shaped if it has actual shape keys + if (def.type === "object") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; } - catch (e) { - await runManager?.handleChainError(e); - throw e; + // Record type is shapeless (dynamic key-value mapping) + if (def.type === "record") { + return true; } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); } - getGraph(config) { - const graph = new Graph(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let currentLastNode = null; - this.steps.forEach((step, index) => { - const stepGraph = step.getGraph(config); - if (index !== 0) { - stepGraph.trimFirstNode(); - } - if (index !== this.steps.length - 1) { - stepGraph.trimLastNode(); - } - graph.extend(stepGraph); - const stepFirstNode = stepGraph.firstNode(); - if (!stepFirstNode) { - throw new Error(`Runnable ${step} has no first node`); - } - if (currentLastNode) { - graph.addEdge(currentLastNode, stepFirstNode); - } - currentLastNode = stepGraph.lastNode(); - }); - return graph; + // For other schemas, check if they have a `shape` property + // If they don't have shape, they're likely shapeless + if (typeof schema === "object" && schema !== null && !("shape" in schema)) { + return true; } - pipe(coerceable) { - if (RunnableSequence.isRunnableSequence(coerceable)) { - return new RunnableSequence({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle, - ]), - last: coerceable.last, - name: this.name ?? coerceable.name, - }); - } - else { - return new RunnableSequence({ - first: this.first, - middle: [...this.middle, this.last], - last: _coerceToRunnable(coerceable), - name: this.name, - }); - } + return false; +} +/** + * Determines if the provided Zod schema should be treated as a simple string schema + * that maps to DynamicTool. This aligns with the type-level constraint of + * InteropZodType which only matches basic string schemas. + * If the provided schema is just z.string(), we can make the determination that + * the tool is just a generic string tool that doesn't require any input validation. + * + * This function only returns true for basic ZodString schemas, including: + * - Basic string schemas (z.string()) + * - String schemas with validations (z.string().min(1), z.string().email(), etc.) + * + * This function returns false for everything else, including: + * - String schemas with defaults (z.string().default("value")) + * - Branded string schemas (z.string().brand<"UserId">()) + * - String schemas with catch operations (z.string().catch("default")) + * - Optional/nullable string schemas (z.string().optional()) + * - Transformed schemas (z.string().transform() or z.object().transform()) + * - Object or record schemas, even if they're empty + * - Any other schema type + * + * @param schema The Zod schema to check. + * @returns {boolean} True if the schema is a basic ZodString, false otherwise. + */ +function isSimpleStringZodSchema(schema) { + if (!isInteropZodSchema(schema)) { + return false; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && Runnable.isRunnable(thing); + // For v3 schemas + if (isZodSchemaV3(schema)) { + // @ts-expect-error - zod v3 types are not compatible with zod v4 types + const def = schema._def; + // Only accept basic ZodString + return def.typeName === "ZodString"; } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from([first, ...runnables], nameOrFields) { - let extra = {}; - if (typeof nameOrFields === "string") { - extra.name = nameOrFields; + // For v4 schemas + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + // Only accept basic string type + return def.type === "string"; + } + return false; +} +/** + * Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). + * + * @param obj The value to check. + * @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. + */ +function isInteropZodObject(obj) { + if (isZodSchemaV3(obj)) { + // Zod v3 object schemas have _def.typeName === "ZodObject" + if (typeof obj === "object" && + obj !== null && + "_def" in obj && + typeof obj._def === "object" && + obj._def !== null && + "typeName" in obj._def && + obj._def.typeName === "ZodObject") { + return true; } - else if (nameOrFields !== undefined) { - extra = nameOrFields; + } + if (isZodSchemaV4(obj)) { + // Zod v4 object schemas have _zod.def.type === "object" + if (typeof obj === "object" && + obj !== null && + "_zod" in obj && + typeof obj._zod === "object" && + obj._zod !== null && + "def" in obj._zod && + typeof obj._zod.def === "object" && + obj._zod.def !== null && + "type" in obj._zod.def && + obj._zod.def.type === "object") { + return true; } - return new RunnableSequence({ - ...extra, - first: _coerceToRunnable(first), - middle: runnables.slice(0, -1).map(_coerceToRunnable), - last: _coerceToRunnable(runnables[runnables.length - 1]), - }); } + return false; } /** - * A runnable that runs a mapping of runnables in parallel, - * and returns a mapping of their outputs. - * @example - * ```typescript - * const mapChain = RunnableMap.from({ - * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( - * new ChatAnthropic({}), - * ), - * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( - * new ChatAnthropic({}), - * ), - * }); - * const result = await mapChain.invoke({ topic: "bear" }); - * ``` + * Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @returns {InteropZodObjectShape} The shape of the object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. */ -class RunnableMap extends Runnable { - static lc_name() { - return "RunnableMap"; +function getInteropZodObjectShape(schema) { + if (isZodSchemaV3(schema)) { + return schema.shape; } - getStepsKeys() { - return Object.keys(this.steps); + if (isZodSchemaV4(schema)) { + return schema._zod.def.shape; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "steps", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) { - this.steps[key] = _coerceToRunnable(value); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Extends a Zod object schema with additional fields, supporting both Zod v3 and v4. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @param {InteropZodObjectShape} extension - The fields to add to the schema. + * @returns {InteropZodObject} The extended Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function extendInteropZodObject(schema, extension) { + if (isZodSchemaV3(schema)) { + return schema.extend(extension); + } + if (isZodSchemaV4(schema)) { + return util.extend(schema, extension); + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a partial version of a Zod object schema, making all fields optional. + * Supports both Zod v3 and v4. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @returns {InteropZodObject} The partial Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function interopZodObjectPartial(schema) { + if (isZodSchemaV3(schema)) { + // z3: .partial() exists and works as expected + return schema.partial(); + } + if (isZodSchemaV4(schema)) { + // z4: util.partial exists and works as expected + return util.partial($ZodOptional, schema, undefined); + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function interopZodObjectPassthrough(schema) { + if (isInteropZodObject(schema)) { + if (isZodSchemaV3(schema)) { + return schema.passthrough(); + } + if (isZodSchemaV4(schema)) { + // Type reassign since ZodObjectV4 assumes that generics should be washed + const objectSchema = schema; + return clone(objectSchema, { + ...objectSchema._zod.def, + catchall: _unknown($ZodUnknown), + }); } } - static from(steps) { - return new RunnableMap({ steps }); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a getter function for the default value of a Zod schema, if one is defined. + * Supports both Zod v3 and v4 schemas. If the schema has a default value, + * the returned function will return that value when called. If no default is defined, + * returns undefined. + * + * @template T - The type of the Zod schema. + * @param {T} schema - The Zod schema instance (either v3 or v4). + * @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set. + */ +function getInteropZodDefaultGetter(schema) { + if (isZodSchemaV3(schema)) { + try { + const defaultValue = schema.parse(undefined); + return () => defaultValue; + } + catch { + return undefined; + } } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { - input, - }, config.runId, undefined, undefined, undefined, config?.runName); - delete config.runId; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const output = {}; + if (isZodSchemaV4(schema)) { try { - const promises = Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`map:key:${key}`), - })); - }); - await raceWithSignal(Promise.all(promises), options?.signal); + const defaultValue = parse(schema, undefined); + return () => defaultValue; } - catch (e) { - await runManager?.handleChainError(e); - throw e; + catch { + return undefined; } - await runManager?.handleChainEnd(output); - return output; } - async *_transform(generator, runManager, options) { - // shallow copy steps to ignore changes while iterating - const steps = { ...this.steps }; - // each step gets a copy of the input iterator - const inputCopies = atee(generator, Object.keys(steps).length); - // start the first iteration of each output iterator - const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { - const gen = runnable.transform(inputCopies[i], patchConfig(options, { - callbacks: runManager?.getChild(`map:key:${key}`), - })); - return [key, gen.next().then((result) => ({ key, gen, result }))]; - })); - // yield chunks as they become available, - // starting new iterations as needed, - // until all iterators are done - while (tasks.size) { - const promise = Promise.race(tasks.values()); - const { key, result, gen } = await raceWithSignal(promise, options?.signal); - tasks.delete(key); - if (!result.done) { - yield { [key]: result.value }; - tasks.set(key, gen.next().then((result) => ({ key, gen, result }))); - } + return undefined; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_schema.js + + + + + +/** + * Converts a Zod schema or JSON schema to a JSON schema. + * @param schema - The schema to convert. + * @returns The converted schema. + */ +function json_schema_toJsonSchema(schema) { + if (isZodSchemaV4(schema)) { + return toJSONSchema(schema); + } + if (isZodSchemaV3(schema)) { + return zodToJsonSchema_zodToJsonSchema(schema); + } + return schema; +} +/** + * Validates if a JSON schema validates only strings. May return false negatives in some edge cases + * (like recursive or unresolvable refs). + * + * @param schema - The schema to validate. + * @returns `true` if the schema validates only strings, `false` otherwise. + */ +function validatesOnlyStrings(schema) { + // Null, undefined, or empty schema + if (!schema || + typeof schema !== "object" || + Object.keys(schema).length === 0 || + Array.isArray(schema)) { + return false; // Validates anything, not just strings + } + // Explicit type constraint + if ("type" in schema) { + if (typeof schema.type === "string") { + return schema.type === "string"; + } + if (Array.isArray(schema.type)) { + // not sure why someone would do `"type": ["string"]` or especially `"type": ["string", + // "string", "string", ...]` but we're not here to judge + return schema.type.every((t) => t === "string"); + } + return false; // Invalid or non-string type + } + // Enum with only string values + if ("enum" in schema) { + return (Array.isArray(schema.enum) && + schema.enum.length > 0 && + schema.enum.every((val) => typeof val === "string")); + } + // String constant + if ("const" in schema) { + return typeof schema.const === "string"; + } + // Schema combinations + if ("allOf" in schema && Array.isArray(schema.allOf)) { + // If any subschema validates only strings, then the overall schema validates only strings + return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); + } + if (("anyOf" in schema && Array.isArray(schema.anyOf)) || + ("oneOf" in schema && Array.isArray(schema.oneOf))) { + const subschemas = ("anyOf" in schema ? schema.anyOf : schema.oneOf); + // All subschemas must validate only strings + return (subschemas.length > 0 && + subschemas.every((subschema) => validatesOnlyStrings(subschema))); + } + // We're not going to try on this one, it's too complex - we just assume if it has a "not" key and hasn't matched one of the above checks, it's not a string schema. + if ("not" in schema) { + return false; // The not case can validate non-strings + } + if ("$ref" in schema && typeof schema.$ref === "string") { + const ref = schema.$ref; + const resolved = dereference(schema); + if (resolved[ref]) { + return validatesOnlyStrings(resolved[ref]); } + return false; } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + // ignore recursive refs and other cases where type is omitted for now + // ignore other cases for now where type is omitted + return false; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js + + + + +function nodeDataStr(id, data) { + if (id !== undefined && !wrapper_validate(id)) { + return id; } - async stream(input, options) { - async function* generator() { - yield input; + else if (isRunnableInterface(data)) { + try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") + ? dataStr.slice("Runnable".length) + : dataStr; + return dataStr; } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + catch (error) { + return data.getName(); + } + } + else { + return data.name ?? "UnknownSchema"; } } -/** - * A runnable that wraps a traced LangSmith function. - */ -class RunnableTraceable extends Runnable { - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_serializable", { +function nodeDataJson(node) { + // if node.data implements Runnable + if (isRunnableInterface(node.data)) { + return { + type: "runnable", + data: { + id: node.data.lc_id, + name: node.data.getName(), + }, + }; + } + else { + return { + type: "schema", + data: { ...json_schema_toJsonSchema(node.data.schema), title: node.data.name }, + }; + } +} +class Graph { + constructor(params) { + Object.defineProperty(this, "nodes", { enumerable: true, configurable: true, writable: true, - value: false + value: {} }); - Object.defineProperty(this, "lc_namespace", { + Object.defineProperty(this, "edges", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "runnables"] + value: [] }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + this.nodes = params?.nodes ?? this.nodes; + this.edges = params?.edges ?? this.edges; + } + // Convert the graph to a JSON-serializable format. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + toJSON() { + const stableNodeIds = {}; + Object.values(this.nodes).forEach((node, i) => { + stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; }); - if (!isTraceableFunction(fields.func)) { - throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + return { + nodes: Object.values(this.nodes).map((node) => ({ + id: stableNodeIds[node.id], + ...nodeDataJson(node), + })), + edges: this.edges.map((edge) => { + const item = { + source: stableNodeIds[edge.source], + target: stableNodeIds[edge.target], + }; + if (typeof edge.data !== "undefined") { + item.data = edge.data; + } + if (typeof edge.conditional !== "undefined") { + item.conditional = edge.conditional; + } + return item; + }), + }; + } + addNode(data, id, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + metadata) { + if (id !== undefined && this.nodes[id] !== undefined) { + throw new Error(`Node with id ${id} already exists`); } - this.func = fields.func; + const nodeId = id ?? v4(); + const node = { + id: nodeId, + data, + name: nodeDataStr(id, data), + metadata, + }; + this.nodes[nodeId] = node; + return node; } - async invoke(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const callbacks = await getCallbackManagerForConfig(config); - const promise = this.func(patchConfig(config, { callbacks }), input); - return raceWithSignal(promise, config?.signal); + removeNode(node) { + // Remove the node from the nodes map + delete this.nodes[node.id]; + // Filter out edges connected to the node + this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); } - async *_streamIterator(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const result = await this.invoke(input, options); - if (iter_isAsyncIterable(result)) { - for await (const item of result) { - config?.signal?.throwIfAborted(); - yield item; - } - return; + addEdge(source, target, data, conditional) { + if (this.nodes[source.id] === undefined) { + throw new Error(`Source node ${source.id} not in graph`); } - if (isIterator(result)) { - while (true) { - config?.signal?.throwIfAborted(); - const state = result.next(); - if (state.done) - break; - yield state.value; - } - return; + if (this.nodes[target.id] === undefined) { + throw new Error(`Target node ${target.id} not in graph`); } - yield result; - } - static from(func) { - return new RunnableTraceable({ func }); + const edge = { + source: source.id, + target: target.id, + data, + conditional, + }; + this.edges.push(edge); + return edge; } -} -function assertNonTraceableFunction(func) { - if (isTraceableFunction(func)) { - throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); + firstNode() { + return _firstNode(this); } -} -/** - * A runnable that wraps an arbitrary function that takes a single argument. - * @example - * ```typescript - * import { RunnableLambda } from "@langchain/core/runnables"; - * - * const add = (input: { x: number; y: number }) => input.x + input.y; - * - * const multiply = (input: { value: number; multiplier: number }) => - * input.value * input.multiplier; - * - * // Create runnables for the functions - * const addLambda = RunnableLambda.from(add); - * const multiplyLambda = RunnableLambda.from(multiply); - * - * // Chain the lambdas for a mathematical operation - * const chainedLambda = addLambda.pipe((result) => - * multiplyLambda.invoke({ value: result, multiplier: 2 }) - * ); - * - * // Example invocation of the chainedLambda - * const result = await chainedLambda.invoke({ x: 2, y: 3 }); - * - * // Will log "10" (since (2 + 3) * 2 = 10) - * ``` - */ -class base_RunnableLambda extends Runnable { - static lc_name() { - return "RunnableLambda"; + lastNode() { + return _lastNode(this); } - constructor(fields) { - if (isTraceableFunction(fields.func)) { - // eslint-disable-next-line no-constructor-return - return RunnableTraceable.from(fields.func); + /** + * Add all nodes and edges from another graph. + * Note this doesn't check for duplicates, nor does it connect the graphs. + */ + extend(graph, prefix = "") { + let finalPrefix = prefix; + const nodeIds = Object.values(graph.nodes).map((node) => node.id); + if (nodeIds.every(wrapper_validate)) { + finalPrefix = ""; } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const prefixed = (id) => { + return finalPrefix ? `${finalPrefix}:${id}` : id; + }; + Object.entries(graph.nodes).forEach(([key, value]) => { + this.nodes[prefixed(key)] = { ...value, id: prefixed(key) }; }); - assertNonTraceableFunction(fields.func); - this.func = fields.func; - } - static from(func) { - return new base_RunnableLambda({ - func, + const newEdges = graph.edges.map((edge) => { + return { + ...edge, + source: prefixed(edge.source), + target: prefixed(edge.target), + }; }); + // Add all edges from the other graph + this.edges = [...this.edges, ...newEdges]; + const first = graph.firstNode(); + const last = graph.lastNode(); + return [ + first ? { id: prefixed(first.id), data: first.data } : undefined, + last ? { id: prefixed(last.id), data: last.data } : undefined, + ]; } - async _invoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, - }); - void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - let output = await this.func(input, { - ...childConfig, - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) { - throw new Error("Recursion limit reached."); - } - output = await output.invoke(input, { - ...childConfig, - recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, - }); - } - else if (iter_isAsyncIterable(output)) { - let finalOutput; - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - // Make a best effort to gather, for any type that supports concat. - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = chunk; - } - } - } - output = finalOutput; - } - else if (isIterableIterator(output)) { - let finalOutput; - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - // Make a best effort to gather, for any type that supports concat. - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = chunk; - } - } - } - output = finalOutput; - } - resolve(output); - } - catch (e) { - reject(e); - } - }); - }); + trimFirstNode() { + const firstNode = this.firstNode(); + if (firstNode && _firstNode(this, [firstNode.id])) { + this.removeNode(firstNode); + } } - async invoke(input, options) { - return this._callWithConfig(this._invoke.bind(this), input, options); + trimLastNode() { + const lastNode = this.lastNode(); + if (lastNode && _lastNode(this, [lastNode.id])) { + this.removeNode(lastNode); + } } - async *_transform(generator, runManager, config) { - let finalChunk; - for await (const chunk of generator) { - if (finalChunk === undefined) { - finalChunk = chunk; + /** + * Return a new graph with all nodes re-identified, + * using their unique, readable names where possible. + */ + reid() { + const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); + const nodeLabelCounts = new Map(); + Object.values(nodeLabels).forEach((label) => { + nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); + }); + const getNodeId = (nodeId) => { + const label = nodeLabels[nodeId]; + if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) { + return label; } else { - // Make a best effort to gather, for any type that supports concat. - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalChunk = concat(finalChunk, chunk); - } - catch (e) { - finalChunk = chunk; - } + return nodeId; } - } - const childConfig = patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }; + return new Graph({ + nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [ + getNodeId(id), + { ...node, id: getNodeId(id) }, + ])), + edges: this.edges.map((edge) => ({ + ...edge, + source: getNodeId(edge.source), + target: getNodeId(edge.target), + })), }); - const output = await new Promise((resolve, reject) => { - void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - const res = await this.func(finalChunk, { - ...childConfig, - config: childConfig, - }); - resolve(res); - } - catch (e) { - reject(e); - } - }); + } + drawMermaid(params) { + const { withStyles, curveStyle, nodeColors = { + default: "fill:#f2f0ff,line-height:1.2", + first: "fill-opacity:0", + last: "fill:#bfb6fc", + }, wrapLabelNWords, } = params ?? {}; + const graph = this.reid(); + const firstNode = graph.firstNode(); + const lastNode = graph.lastNode(); + return drawMermaid(graph.nodes, graph.edges, { + firstNode: firstNode?.id, + lastNode: lastNode?.id, + withStyles, + curveStyle, + nodeColors, + wrapLabelNWords, }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) { - throw new Error("Recursion limit reached."); - } - const stream = await output.stream(finalChunk, childConfig); + } + async drawMermaidPng(params) { + const mermaidSyntax = this.drawMermaid(params); + return drawMermaidPng(mermaidSyntax, { + backgroundColor: params?.backgroundColor, + }); + } +} +/** + * Find the single node that is not a target of any edge. + * Exclude nodes/sources with ids in the exclude list. + * If there is no such node, or there are multiple, return undefined. + * When drawing the graph, this node would be the origin. + */ +function _firstNode(graph, exclude = []) { + const targets = new Set(graph.edges + .filter((edge) => !exclude.includes(edge.source)) + .map((edge) => edge.target)); + const found = []; + for (const node of Object.values(graph.nodes)) { + if (!exclude.includes(node.id) && !targets.has(node.id)) { + found.push(node); + } + } + return found.length === 1 ? found[0] : undefined; +} +/** + * Find the single node that is not a source of any edge. + * Exclude nodes/targets with ids in the exclude list. + * If there is no such node, or there are multiple, return undefined. + * When drawing the graph, this node would be the destination. + */ +function _lastNode(graph, exclude = []) { + const sources = new Set(graph.edges + .filter((edge) => !exclude.includes(edge.target)) + .map((edge) => edge.source)); + const found = []; + for (const node of Object.values(graph.nodes)) { + if (!exclude.includes(node.id) && !sources.has(node.id)) { + found.push(node); + } + } + return found.length === 1 ? found[0] : undefined; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js + +function convertToHttpEventStream(stream) { + const encoder = new TextEncoder(); + const finalStream = new ReadableStream({ + async start(controller) { for await (const chunk of stream) { - yield chunk; + controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); } + controller.enqueue(encoder.encode("event: end\n\n")); + controller.close(); + }, + }); + return IterableReadableStream.fromReadableStream(finalStream); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js + + +function isIterableIterator(thing) { + return (typeof thing === "object" && + thing !== null && + typeof thing[Symbol.iterator] === "function" && + // avoid detecting array/set as iterator + typeof thing.next === "function"); +} +const isIterator = (x) => x != null && + typeof x === "object" && + "next" in x && + typeof x.next === "function"; +function iter_isAsyncIterable(thing) { + return (typeof thing === "object" && + thing !== null && + typeof thing[Symbol.asyncIterator] === + "function"); +} +function* consumeIteratorInContext(context, iter) { + while (true) { + const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true); + if (done) { + break; } - else if (iter_isAsyncIterable(output)) { - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } + else { + yield value; } - else if (isIterableIterator(output)) { - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } + } +} +async function* consumeAsyncIterableInContext(context, iter) { + const iterator = iter[Symbol.asyncIterator](); + while (true) { + const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true); + if (done) { + break; } else { - yield output; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; + yield value; } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } } -/** - * A runnable that runs a mapping of runnables in parallel, - * and returns a mapping of their outputs. - * @example - * ```typescript - * import { - * RunnableLambda, - * RunnableParallel, - * } from "@langchain/core/runnables"; - * - * const addYears = (age: number): number => age + 5; - * const yearsToFifty = (age: number): number => 50 - age; - * const yearsToHundred = (age: number): number => 100 - age; - * - * const addYearsLambda = RunnableLambda.from(addYears); - * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); - * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); - * - * // Pipe will coerce objects into RunnableParallel by default, but we - * // explicitly instantiate one here to demonstrate - * const sequence = addYearsLambda.pipe( - * RunnableParallel.from({ - * years_to_fifty: milestoneFiftyLambda, - * years_to_hundred: milestoneHundredLambda, - * }) - * ); - * - * // Invoke the sequence with a single age input - * const res = sequence.invoke(25); - * - * // { years_to_fifty: 25, years_to_hundred: 75 } - * ``` - */ -class RunnableParallel extends (/* unused pure expression or super */ null && (RunnableMap)) { + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js + + + + + + + + + + + + + + + + + + + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function base_coerceToDict(value, defaultKey) { + return value && + !Array.isArray(value) && + // eslint-disable-next-line no-instanceof/no-instanceof + !(value instanceof Date) && + typeof value === "object" + ? value + : { [defaultKey]: value }; } /** - * A Runnable that can fallback to other Runnables if it fails. - * External APIs (e.g., APIs for a language model) may at times experience - * degraded performance or even downtime. - * - * In these cases, it can be useful to have a fallback Runnable that can be - * used in place of the original Runnable (e.g., fallback to another LLM provider). - * - * Fallbacks can be defined at the level of a single Runnable, or at the level - * of a chain of Runnables. Fallbacks are tried in order until one succeeds or - * all fail. - * - * While you can instantiate a `RunnableWithFallbacks` directly, it is usually - * more convenient to use the `withFallbacks` method on an existing Runnable. - * - * When streaming, fallbacks will only be called on failures during the initial - * stream creation. Errors that occur after a stream starts will not fallback - * to the next Runnable. - * - * @example - * ```typescript - * import { - * RunnableLambda, - * RunnableWithFallbacks, - * } from "@langchain/core/runnables"; - * - * const primaryOperation = (input: string): string => { - * if (input !== "safe") { - * throw new Error("Primary operation failed due to unsafe input"); - * } - * return `Processed: ${input}`; - * }; - * - * // Define a fallback operation that processes the input differently - * const fallbackOperation = (input: string): string => - * `Fallback processed: ${input}`; - * - * const primaryRunnable = RunnableLambda.from(primaryOperation); - * const fallbackRunnable = RunnableLambda.from(fallbackOperation); - * - * // Apply the fallback logic using the .withFallbacks() method - * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); - * - * // Alternatively, create a RunnableWithFallbacks instance manually - * const manualFallbackChain = new RunnableWithFallbacks({ - * runnable: primaryRunnable, - * fallbacks: [fallbackRunnable], - * }); - * - * // Example invocation using .withFallbacks() - * const res = await runnableWithFallback - * .invoke("unsafe input") - * .catch((error) => { - * console.error("Failed after all attempts:", error.message); - * }); - * - * // "Fallback processed: unsafe input" - * - * // Example invocation using manual instantiation - * const res = await manualFallbackChain - * .invoke("safe") - * .catch((error) => { - * console.error("Failed after all attempts:", error.message); - * }); - * - * // "Processed: safe" - * ``` + * A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or + * transformed. */ -class RunnableWithFallbacks extends Runnable { - static lc_name() { - return "RunnableWithFallbacks"; - } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { +class Runnable extends Serializable { + constructor() { + super(...arguments); + Object.defineProperty(this, "lc_runnable", { enumerable: true, configurable: true, writable: true, value: true }); - Object.defineProperty(this, "runnable", { + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "fallbacks", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + getName(suffix) { + const name = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.name ?? this.constructor.lc_name() ?? this.constructor.name; + return suffix ? `${name}${suffix}` : name; + } + /** + * Bind arguments to a Runnable, returning a new Runnable. + * @param kwargs + * @returns A new RunnableBinding that, when invoked, will apply the bound args. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ bound: this, kwargs, config: {} }); + } + /** + * Return a new Runnable that maps a list of inputs to a list of outputs, + * by calling invoke() with each input. + * + * @deprecated This will be removed in the next breaking release. + */ + map() { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableEach({ bound: this }); + } + /** + * Add retry logic to an existing runnable. + * @param fields.stopAfterAttempt The number of attempts to retry. + * @param fields.onFailedAttempt A function that is called when a retry fails. + * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. + */ + withRetry(fields) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields, }); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) { - yield fallback; + /** + * Bind config to a Runnable, returning a new Runnable. + * @param config New configuration parameters to attach to the new runnable. + * @returns A new RunnableBinding with a config matching what's passed. + */ + withConfig(config) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ + bound: this, + config, + kwargs: {}, + }); + } + /** + * Create a new runnable from the current one that will try invoking + * other passed fallback runnables if the initial invocation fails. + * @param fields.fallbacks Other runnables to call if the runnable errors. + * @returns A new RunnableWithFallbacks. + */ + withFallbacks(fields) { + const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableWithFallbacks({ + runnable: this, + fallbacks, + }); + } + _getOptionsList(options, length = 0) { + if (Array.isArray(options) && options.length !== length) { + throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); + } + if (Array.isArray(options)) { + return options.map(ensureConfig); + } + if (length > 1 && !Array.isArray(options) && options.runId) { + console.warn("Provided runId will be used only for the first element of the batch."); + const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); + return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); } + return Array.from({ length }, () => ensureConfig(options)); } - async invoke(input, options) { + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const caller = new async_caller_AsyncCaller({ + maxConcurrency, + onFailedAttempt: (e) => { + throw e; + }, + }); + const batchCalls = inputs.map((input, i) => caller.call(async () => { + try { + const result = await this.invoke(input, configList[i]); + return result; + } + catch (e) { + if (batchOptions?.returnExceptions) { + return e; + } + throw e; + } + })); + return Promise.all(batchCalls); + } + /** + * Default streaming implementation. + * Subclasses should override this method if they support streaming output. + * @param input + * @param options + */ + async *_streamIterator(input, options) { + yield this.invoke(input, options); + } + /** + * Stream output in chunks. + * @param input + * @param options + * @returns A readable stream that is also an iterable. + */ + async stream(input, options) { + // Buffer the first streamed chunk to allow for initial errors + // to surface immediately. const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId, ...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); - const childConfig = patchConfig(otherConfigFields, { - callbacks: runManager?.getChild(), + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this._streamIterator(input, config), + config, }); - const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { - let firstError; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - try { - const output = await runnable.invoke(input, childConfig); - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + _separateRunnableConfigFromCallOptions(options) { + let runnableConfig; + if (options === undefined) { + runnableConfig = ensureConfig(options); + } + else { + runnableConfig = ensureConfig({ + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + runName: options.runName, + configurable: options.configurable, + recursionLimit: options.recursionLimit, + maxConcurrency: options.maxConcurrency, + runId: options.runId, + timeout: options.timeout, + signal: options.signal, + }); + } + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + delete callOptions.runName; + delete callOptions.configurable; + delete callOptions.recursionLimit; + delete callOptions.maxConcurrency; + delete callOptions.runId; + delete callOptions.timeout; + delete callOptions.signal; + return [runnableConfig, callOptions]; + } + async _callWithConfig(func, input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, undefined, undefined, config?.runName ?? this.getName()); + delete config.runId; + let output; + try { + const promise = func.call(this, input, config, runManager); + output = await raceWithSignal(promise, options?.signal); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + return output; + } + /** + * Internal method that handles batching and configuration for a runnable + * It takes a function, input values, and optional configuration, and + * returns a promise that resolves to the output values. + * @param func The function to be executed for each input value. + * @param input The input values to be processed. + * @param config Optional configuration for the function execution. + * @returns A promise that resolves to the output values. + */ + async _batchWithConfig(func, inputs, options, batchOptions) { + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName()); + delete optionsList[i].runId; + return handleStartRes; + })); + let outputs; + try { + const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); + outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); + } + catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); + return outputs; + } + /** + * Helper method to transform an Iterator of Input values into an Iterator of + * Output values, with callbacks. + * Use this to implement `stream()` or `transform()` in Runnable subclasses. + */ + async *_transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (finalInputSupported) { + if (finalInput === undefined) { + finalInput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalInput = concat(finalInput, chunk); + } + catch { + finalInput = undefined; + finalInputSupported = false; + } + } } - catch (e) { - if (firstError === undefined) { - firstError = e; + yield chunk; + } + } + let runManager; + try { + const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), options?.signal, config); + delete config.runId; + runManager = pipe.setup; + const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); + let iterator = pipe.output; + if (streamEventsHandler !== undefined && runManager !== undefined) { + iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + } + const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); + if (streamLogHandler !== undefined && runManager !== undefined) { + iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + } + for await (const chunk of iterator) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch { + finalOutput = undefined; + finalOutputSupported = false; + } } } } - if (firstError === undefined) { - throw new Error("No error stored at end of fallback."); + } + catch (e) { + await runManager?.handleChainError(e, undefined, undefined, undefined, { + inputs: base_coerceToDict(finalInput, "input"), + }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, undefined, undefined, undefined, { inputs: base_coerceToDict(finalInput, "input") }); + } + getGraph(_) { + const graph = new Graph(); + // TODO: Add input schema for runnables + const inputNode = graph.addNode({ + name: `${this.getName()}Input`, + schema: anyType(), + }); + const runnableNode = graph.addNode(this); + // TODO: Add output schemas for runnables + const outputNode = graph.addNode({ + name: `${this.getName()}Output`, + schema: anyType(), + }); + graph.addEdge(inputNode, runnableNode); + graph.addEdge(runnableNode, outputNode); + return graph; + } + /** + * Create a new runnable sequence that runs each individual runnable in series, + * piping the output of one runnable into another runnable or runnable-like. + * @param coerceable A runnable, function, or object whose values are functions or runnables. + * @returns A new runnable sequence. + */ + pipe(coerceable) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableSequence({ + first: this, + last: _coerceToRunnable(coerceable), + }); + } + /** + * Pick keys from the dict output of this runnable. Returns a new runnable. + */ + pick(keys) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return this.pipe(new RunnablePick(keys)); + } + /** + * Assigns new fields to the dict output of this runnable. Returns a new runnable. + */ + assign(mapping) { + return this.pipe( + // eslint-disable-next-line @typescript-eslint/no-use-before-define + new RunnableAssign( + // eslint-disable-next-line @typescript-eslint/no-use-before-define + new RunnableMap({ steps: mapping }))); + } + /** + * Default implementation of transform, which buffers input and then calls stream. + * Subclasses should override this method if they can start producing output while + * input is still being generated. + * @param generator + * @param options + */ + async *transform(generator, options) { + let finalChunk; + for await (const chunk of generator) { + if (finalChunk === undefined) { + finalChunk = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + // This method should throw an error if gathering fails. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalChunk = concat(finalChunk, chunk); } - await runManager?.handleChainError(firstError); - throw firstError; - }); - return res; + } + yield* this._streamIterator(finalChunk, ensureConfig(options)); } - async *_streamIterator(input, options) { + /** + * Stream all output from a runnable, as reported to the callback system. + * This includes all inner runs of LLMs, Retrievers, Tools, etc. + * Output is streamed as Log objects, which include a list of + * jsonpatch ops that describe how the state of the run has changed in each + * step, and the final state of the run. + * The jsonpatch ops can be applied in order to construct state. + * @param input + * @param options + * @param streamOptions + */ + async *streamLog(input, options, streamOptions) { + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "original", + }); const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId, ...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); - let firstError; - let stream; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - const childConfig = patchConfig(otherConfigFields, { - callbacks: runManager?.getChild(), - }); + yield* this._streamLog(input, logStreamCallbackHandler, config); + } + async *_streamLog(input, logStreamCallbackHandler, config) { + const { callbacks } = config; + if (callbacks === undefined) { + // eslint-disable-next-line no-param-reassign + config.callbacks = [logStreamCallbackHandler]; + } + else if (Array.isArray(callbacks)) { + // eslint-disable-next-line no-param-reassign + config.callbacks = callbacks.concat([logStreamCallbackHandler]); + } + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(logStreamCallbackHandler, true); + // eslint-disable-next-line no-param-reassign + config.callbacks = copiedCallbacks; + } + const runnableStreamPromise = this.stream(input, config); + async function consumeRunnableStream() { try { - const originalStream = await runnable.stream(input, childConfig); - stream = consumeAsyncIterableInContext(childConfig, originalStream); - break; - } - catch (e) { - if (firstError === undefined) { - firstError = e; + const runnableStream = await runnableStreamPromise; + for await (const chunk of runnableStream) { + const patch = new RunLogPatch({ + ops: [ + { + op: "add", + path: "/streamed_output/-", + value: chunk, + }, + ], + }); + await logStreamCallbackHandler.writer.write(patch); } } + finally { + await logStreamCallbackHandler.writer.close(); + } } - if (stream === undefined) { - const error = firstError ?? new Error("No error stored at end of fallback."); - await runManager?.handleChainError(error); - throw error; - } - let output; + const runnableStreamConsumePromise = consumeRunnableStream(); try { - for await (const chunk of stream) { - yield chunk; - try { - output = output === undefined ? output : concat(output, chunk); - } - catch (e) { - output = undefined; - } + for await (const log of logStreamCallbackHandler) { + yield log; } } - catch (e) { - await runManager?.handleChainError(e); - throw e; + finally { + await runnableStreamConsumePromise; } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) { - throw new Error("Not implemented."); + streamEvents(input, options, streamOptions) { + let stream; + if (options.version === "v1") { + stream = this._streamEventsV1(input, options, streamOptions); } - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let firstError; - for (const runnable of this.runnables()) { - configList[0].signal?.throwIfAborted(); + else if (options.version === "v2") { + stream = this._streamEventsV2(input, options, streamOptions); + } + else { + throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + } + if (options.encoding === "text/event-stream") { + return convertToHttpEventStream(stream); + } + else { + return IterableReadableStream.fromAsyncGenerator(stream); + } + } + async *_streamEventsV2(input, options, streamOptions) { + const eventStreamer = new EventStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + }); + const config = ensureConfig(options); + const runId = config.runId ?? v4(); + config.runId = runId; + const callbacks = config.callbacks; + if (callbacks === undefined) { + config.callbacks = [eventStreamer]; + } + else if (Array.isArray(callbacks)) { + config.callbacks = callbacks.concat(eventStreamer); + } + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(eventStreamer, true); + // eslint-disable-next-line no-param-reassign + config.callbacks = copiedCallbacks; + } + const abortController = new AbortController(); + // Call the runnable in streaming mode, + // add each chunk to the output stream + const outerThis = this; + async function consumeRunnableStream() { try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { - callbacks: runManager?.getChild(), - })), batchOptions); - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); - return outputs; - } - catch (e) { - if (firstError === undefined) { - firstError = e; + let signal; + if (options?.signal) { + if ("any" in AbortSignal) { + // Use native AbortSignal.any() if available (Node 19+) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + signal = AbortSignal.any([ + abortController.signal, + options.signal, + ]); + } + else { + // Fallback for Node 18 and below - just use the provided signal + signal = options.signal; + // Ensure we still abort our controller when the parent signal aborts + options.signal.addEventListener("abort", () => { + abortController.abort(); + }, { once: true }); + } + } + else { + signal = abortController.signal; + } + const runnableStream = await outerThis.stream(input, { + ...config, + signal, + }); + const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + for await (const _ of tappedStream) { + // Just iterate so that the callback handler picks up events + if (abortController.signal.aborted) + break; } } + finally { + await eventStreamer.finish(); + } } - if (!firstError) { - throw new Error("No error stored at end of fallbacks."); + const runnableStreamConsumePromise = consumeRunnableStream(); + let firstEventSent = false; + let firstEventRunId; + try { + for await (const event of eventStreamer) { + // This is a work-around an issue where the inputs into the + // chain are not available until the entire input is consumed. + // As a temporary solution, we'll modify the input to be the input + // that was passed into the chain. + if (!firstEventSent) { + event.data.input = input; + firstEventSent = true; + firstEventRunId = event.run_id; + yield event; + continue; + } + if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { + // If it's the end event corresponding to the root runnable + // we dont include the input in the event since it's guaranteed + // to be included in the first event. + if (event.data?.input) { + delete event.data.input; + } + } + yield event; + } } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; - } -} -// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type -function _coerceToRunnable(coerceable) { - if (typeof coerceable === "function") { - return new base_RunnableLambda({ func: coerceable }); - } - else if (Runnable.isRunnable(coerceable)) { - return coerceable; - } - else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) { - runnables[key] = _coerceToRunnable(value); + finally { + abortController.abort(); + await runnableStreamConsumePromise; } - return new RunnableMap({ - steps: runnables, - }); - } - else { - throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); - } -} -/** - * A runnable that assigns key-value pairs to inputs of type `Record`. - * @example - * ```typescript - * import { - * RunnableAssign, - * RunnableLambda, - * RunnableParallel, - * } from "@langchain/core/runnables"; - * - * const calculateAge = (x: { birthYear: number }): { age: number } => { - * const currentYear = new Date().getFullYear(); - * return { age: currentYear - x.birthYear }; - * }; - * - * const createGreeting = (x: { name: string }): { greeting: string } => { - * return { greeting: `Hello, ${x.name}!` }; - * }; - * - * const mapper = RunnableParallel.from({ - * age_step: RunnableLambda.from(calculateAge), - * greeting_step: RunnableLambda.from(createGreeting), - * }); - * - * const runnableAssign = new RunnableAssign({ mapper }); - * - * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); - * - * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } - * ``` - */ -class RunnableAssign extends Runnable { - static lc_name() { - return "RunnableAssign"; } - constructor(fields) { - // eslint-disable-next-line no-instanceof/no-instanceof - if (fields instanceof RunnableMap) { - // eslint-disable-next-line no-param-reassign - fields = { mapper: fields }; - } - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true + async *_streamEventsV1(input, options, streamOptions) { + let runLog; + let hasEncounteredStartEvent = false; + const config = ensureConfig(options); + const rootTags = config.tags ?? []; + const rootMetadata = config.metadata ?? {}; + const rootName = config.runName ?? this.getName(); + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "streaming_events", }); - Object.defineProperty(this, "mapper", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + const rootEventFilter = new _RootEventFilter({ + ...streamOptions, }); - this.mapper = fields.mapper; - } - async invoke(input, options) { - const mapperResult = await this.mapper.invoke(input, options); - return { - ...input, - ...mapperResult, - }; - } - async *_transform(generator, runManager, options) { - // collect mapper keys - const mapperKeys = this.mapper.getStepsKeys(); - // create two input gens, one for the mapper, one for the input - const [forPassthrough, forMapper] = atee(generator); - // create mapper output gen - const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); - // start the mapper - const firstMapperChunkPromise = mapperOutput.next(); - // yield the passthrough - for await (const chunk of forPassthrough) { - if (typeof chunk !== "object" || Array.isArray(chunk)) { - throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); + const logStream = this._streamLog(input, logStreamCallbackHandler, config); + for await (const log of logStream) { + if (!runLog) { + runLog = RunLog.fromRunLogPatch(log); } - const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); - if (Object.keys(filtered).length > 0) { - yield filtered; + else { + runLog = runLog.concat(log); + } + if (runLog.state === undefined) { + throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + } + // Yield the start event for the root runnable if it hasn't been seen. + // The root run is never filtered out + if (!hasEncounteredStartEvent) { + hasEncounteredStartEvent = true; + const state = { ...runLog.state }; + const event = { + run_id: state.id, + event: `on_${state.type}_start`, + name: rootName, + tags: rootTags, + metadata: rootMetadata, + data: { + input, + }, + }; + if (rootEventFilter.includeEvent(event, state.type)) { + yield event; + } + } + const paths = log.ops + .filter((op) => op.path.startsWith("/logs/")) + .map((op) => op.path.split("/")[2]); + const dedupedPaths = [...new Set(paths)]; + for (const path of dedupedPaths) { + let eventType; + let data = {}; + const logEntry = runLog.state.logs[path]; + if (logEntry.end_time === undefined) { + if (logEntry.streamed_output.length > 0) { + eventType = "stream"; + } + else { + eventType = "start"; + } + } + else { + eventType = "end"; + } + if (eventType === "start") { + // Include the inputs with the start event if they are available. + // Usually they will NOT be available for components that operate + // on streams, since those components stream the input and + // don't know its final value until the end of the stream. + if (logEntry.inputs !== undefined) { + data.input = logEntry.inputs; + } + } + else if (eventType === "end") { + if (logEntry.inputs !== undefined) { + data.input = logEntry.inputs; + } + data.output = logEntry.final_output; + } + else if (eventType === "stream") { + const chunkCount = logEntry.streamed_output.length; + if (chunkCount !== 1) { + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); + } + data = { chunk: logEntry.streamed_output[0] }; + // Clean up the stream, we don't need it anymore. + // And this avoids duplicates as well! + logEntry.streamed_output = []; + } + yield { + event: `on_${logEntry.type}_${eventType}`, + name: logEntry.name, + run_id: logEntry.id, + tags: logEntry.tags, + metadata: logEntry.metadata, + data, + }; + } + // Finally, we take care of the streaming output from the root chain + // if there is any. + const { state } = runLog; + if (state.streamed_output.length > 0) { + const chunkCount = state.streamed_output.length; + if (chunkCount !== 1) { + throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state.name}"`); + } + const data = { chunk: state.streamed_output[0] }; + // Clean up the stream, we don't need it anymore. + state.streamed_output = []; + const event = { + event: `on_${state.type}_stream`, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + name: rootName, + data, + }; + if (rootEventFilter.includeEvent(event, state.type)) { + yield event; + } } } - // yield the mapper output - yield (await firstMapperChunkPromise).value; - for await (const chunk of mapperOutput) { - yield chunk; + const state = runLog?.state; + if (state !== undefined) { + // Finally, yield the end event for the root runnable. + const event = { + event: `on_${state.type}_end`, + name: rootName, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + data: { + output: state.final_output, + }, + }; + if (rootEventFilter.includeEvent(event, state.type)) + yield event; } } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnable(thing) { + return isRunnableInterface(thing); } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError, }) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableBinding({ + bound: this, + config: {}, + configFactories: [ + (config) => ({ + callbacks: [ + new RootListenersTracer({ + config, + onStart, + onEnd, + onError, + }), + ], + }), + ], }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + /** + * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` + * which contains the runnable, name, description and schema. + * + * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. + * + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. + */ + asTool(fields) { + return convertRunnableToTool(this, fields); } } /** - * A runnable that assigns key-value pairs to inputs of type `Record`. - * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. + * Wraps a runnable and applies partial config upon invocation. + * * @example * ```typescript - * import { RunnablePick } from "@langchain/core/runnables"; + * import { + * type RunnableConfig, + * RunnableLambda, + * } from "@langchain/core/runnables"; * - * const inputData = { - * name: "John", - * age: 30, - * city: "New York", - * country: "USA", - * email: "john.doe@example.com", - * phone: "+1234567890", + * const enhanceProfile = ( + * profile: Record, + * config?: RunnableConfig + * ) => { + * if (config?.configurable?.role) { + * return { ...profile, role: config.configurable.role }; + * } + * return profile; * }; * - * const basicInfoRunnable = new RunnablePick(["name", "city"]); + * const runnable = RunnableLambda.from(enhanceProfile); * - * // Example invocation - * const res = await basicInfoRunnable.invoke(inputData); + * // Bind configuration to the runnable to set the user's role dynamically + * const adminRunnable = runnable.bind({ configurable: { role: "Admin" } }); + * const userRunnable = runnable.bind({ configurable: { role: "User" } }); * - * // { name: 'John', city: 'New York' } + * const result1 = await adminRunnable.invoke({ + * name: "Alice", + * email: "alice@example.com" + * }); + * + * // { name: "Alice", email: "alice@example.com", role: "Admin" } + * + * const result2 = await userRunnable.invoke({ + * name: "Bob", + * email: "bob@example.com" + * }); + * + * // { name: "Bob", email: "bob@example.com", role: "User" } * ``` */ -class RunnablePick extends Runnable { +class RunnableBinding extends Runnable { static lc_name() { - return "RunnablePick"; + return "RunnableBinding"; } constructor(fields) { - if (typeof fields === "string" || Array.isArray(fields)) { - // eslint-disable-next-line no-param-reassign - fields = { keys: fields }; - } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, @@ -100528,1191 +110546,1121 @@ class RunnablePick extends Runnable { writable: true, value: true }); - Object.defineProperty(this, "keys", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.keys = fields.keys; - } - async _pick(input) { - if (typeof this.keys === "string") { - return input[this.keys]; - } - else { - const picked = this.keys - .map((key) => [key, input[key]]) - .filter((v) => v[1] !== undefined); - return picked.length === 0 ? undefined : Object.fromEntries(picked); - } - } - async invoke(input, options) { - return this._callWithConfig(this._pick.bind(this), input, options); - } - async *_transform(generator) { - for await (const chunk of generator) { - const picked = await this._pick(chunk); - if (picked !== undefined) { - yield picked; - } - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config, - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -} -class RunnableToolLike extends RunnableBinding { - constructor(fields) { - const sequence = RunnableSequence.from([ - base_RunnableLambda.from(async (input) => { - let toolInput; - if (_isToolCall(input)) { - try { - toolInput = await this.schema.parseAsync(input.args); - } - catch (e) { - throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); - } - } - else { - toolInput = input; - } - return toolInput; - }).withConfig({ runName: `${fields.name}:parse_input` }), - fields.bound, - ]).withConfig({ runName: fields.name }); - super({ - bound: sequence, - config: fields.config ?? {}, - }); - Object.defineProperty(this, "name", { + Object.defineProperty(this, "bound", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "description", { + Object.defineProperty(this, "config", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "schema", { + Object.defineProperty(this, "kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - static lc_name() { - return "RunnableToolLike"; - } -} -/** - * Given a runnable and a Zod schema, convert the runnable to a tool. - * - * @template RunInput The input type for the runnable. - * @template RunOutput The output type for the runnable. - * - * @param {Runnable} runnable The runnable to convert to a tool. - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ -function convertRunnableToTool(runnable, fields) { - const name = fields.name ?? runnable.getName(); - const description = fields.description ?? fields.schema?.description; - if (fields.schema.constructor === z.ZodString) { - return new RunnableToolLike({ - name, - description, - schema: z - .object({ - input: z.string(), - }) - .transform((input) => input.input), - bound: runnable, - }); - } - return new RunnableToolLike({ - name, - description, - schema: fields.schema, - bound: runnable, - }); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js - -/** - * Message responsible for deleting other messages. - */ -class RemoveMessage extends BaseMessage { - constructor(fields) { - super({ - ...fields, - content: "", - }); - /** - * The ID of the message to remove. - */ - Object.defineProperty(this, "id", { + Object.defineProperty(this, "configFactories", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.id = fields.id; - } - _getType() { - return "remove"; - } - get _printableFields() { - return { - ...super._printableFields, - id: this.id, - }; - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js - - - - - - - - - - -const _isMessageType = (msg, types) => { - const typesAsStrings = [ - ...new Set(types?.map((t) => { - if (typeof t === "string") { - return t; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const instantiatedMsgClass = new t({}); - if (!("getType" in instantiatedMsgClass) || - typeof instantiatedMsgClass.getType !== "function") { - throw new Error("Invalid type provided."); - } - return instantiatedMsgClass.getType(); - })), - ]; - const msgType = msg.getType(); - return typesAsStrings.some((t) => t === msgType); -}; -function filterMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - return _filterMessages(messagesOrOptions, options); - } - return RunnableLambda.from((input) => { - return _filterMessages(input, messagesOrOptions); - }); -} -function _filterMessages(messages, options = {}) { - const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds, } = options; - const filtered = []; - for (const msg of messages) { - if (excludeNames && msg.name && excludeNames.includes(msg.name)) { - continue; - } - else if (excludeTypes && _isMessageType(msg, excludeTypes)) { - continue; - } - else if (excludeIds && msg.id && excludeIds.includes(msg.id)) { - continue; - } - // default to inclusion when no inclusion criteria given. - if (!(includeTypes || includeIds || includeNames)) { - filtered.push(msg); - } - else if (includeNames && - msg.name && - includeNames.some((iName) => iName === msg.name)) { - filtered.push(msg); - } - else if (includeTypes && _isMessageType(msg, includeTypes)) { - filtered.push(msg); - } - else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) { - filtered.push(msg); - } - } - return filtered; -} -function mergeMessageRuns(messages) { - if (Array.isArray(messages)) { - return _mergeMessageRuns(messages); - } - return RunnableLambda.from(_mergeMessageRuns); -} -function _mergeMessageRuns(messages) { - if (!messages.length) { - return []; - } - const merged = []; - for (const msg of messages) { - const curr = msg; - const last = merged.pop(); - if (!last) { - merged.push(curr); - } - else if (curr.getType() === "tool" || - !(curr.getType() === last.getType())) { - merged.push(last, curr); - } - else { - const lastChunk = convertToChunk(last); - const currChunk = convertToChunk(curr); - const mergedChunks = lastChunk.concat(currChunk); - if (typeof lastChunk.content === "string" && - typeof currChunk.content === "string") { - mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; - } - merged.push(_chunkToMsg(mergedChunks)); - } - } - return merged; -} -function trimMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - const messages = messagesOrOptions; - if (!options) { - throw new Error("Options parameter is required when providing messages."); - } - return _trimMessagesHelper(messages, options); - } - else { - const trimmerOptions = messagesOrOptions; - return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ - runName: "trim_messages", - }); - } -} -async function _trimMessagesHelper(messages, options) { - const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter, } = options; - if (startOn && strategy === "first") { - throw new Error("`startOn` should only be specified if `strategy` is 'last'."); - } - if (includeSystem && strategy === "first") { - throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); - } - let listTokenCounter; - if ("getNumTokens" in tokenCounter) { - listTokenCounter = async (msgs) => { - const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); - return tokenCounts.reduce((sum, count) => sum + count, 0); - }; + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + this.configFactories = fields.configFactories; } - else { - listTokenCounter = async (msgs) => tokenCounter(msgs); + getName(suffix) { + return this.bound.getName(suffix); } - let textSplitterFunc = defaultTextSplitter; - if (textSplitter) { - if ("splitText" in textSplitter) { - textSplitterFunc = textSplitter.splitText; - } - else { - textSplitterFunc = async (text) => textSplitter(text); - } + async _mergeConfig(...options) { + const config = mergeConfigs(this.config, ...options); + return mergeConfigs(config, ...(this.configFactories + ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) + : [])); } - if (strategy === "first") { - return _firstMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - partialStrategy: allowPartial ? "first" : undefined, - endOn, + /** + * Binds the runnable with the specified arguments. + * @param kwargs The arguments to bind the runnable with. + * @returns A new instance of the `RunnableBinding` class that is bound with the specified arguments. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new this.constructor({ + bound: this.bound, + kwargs: { ...this.kwargs, ...kwargs }, + config: this.config, }); } - else if (strategy === "last") { - return _lastMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - allowPartial, - includeSystem, - startOn, - endOn, + withConfig(config) { + return new this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { ...this.config, ...config }, }); } - else { - throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); - } -} -async function _firstMaxTokens(messages, options) { - const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; - let messagesCopy = [...messages]; - let idx = 0; - for (let i = 0; i < messagesCopy.length; i += 1) { - const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; - if ((await tokenCounter(remainingMessages)) <= maxTokens) { - idx = messagesCopy.length - i; - break; - } - } - if (idx < messagesCopy.length - 1 && partialStrategy) { - let includedPartial = false; - if (Array.isArray(messagesCopy[idx].content)) { - const excluded = messagesCopy[idx]; - if (typeof excluded.content === "string") { - throw new Error("Expected content to be an array."); - } - const numBlock = excluded.content.length; - const reversedContent = partialStrategy === "last" - ? [...excluded.content].reverse() - : excluded.content; - for (let i = 1; i <= numBlock; i += 1) { - const partialContent = partialStrategy === "first" - ? reversedContent.slice(0, i) - : reversedContent.slice(-i); - const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - const updatedMessage = _switchTypeToMessage(excluded.getType(), { - ...fields, - content: partialContent, - }); - const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; - if ((await tokenCounter(slicedMessages)) <= maxTokens) { - messagesCopy = slicedMessages; - idx += 1; - includedPartial = true; - } - else { - break; - } - } - if (includedPartial && partialStrategy === "last") { - excluded.content = [...reversedContent].reverse(); - } - } - if (!includedPartial) { - const excluded = messagesCopy[idx]; - let text; - if (Array.isArray(excluded.content) && - excluded.content.some((block) => typeof block === "string" || block.type === "text")) { - const textBlock = excluded.content.find((block) => block.type === "text" && block.text); - text = textBlock?.text; - } - else if (typeof excluded.content === "string") { - text = excluded.content; - } - if (text) { - const splitTexts = await textSplitter(text); - const numSplits = splitTexts.length; - if (partialStrategy === "last") { - splitTexts.reverse(); - } - for (let _ = 0; _ < numSplits - 1; _ += 1) { - splitTexts.pop(); - excluded.content = splitTexts.join(""); - if ((await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <= - maxTokens) { - if (partialStrategy === "last") { - excluded.content = [...splitTexts].reverse().join(""); - } - messagesCopy = [...messagesCopy.slice(0, idx), excluded]; - idx += 1; - break; - } - } - } - } - } - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) { - idx -= 1; - } + withRetry(fields) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + return new RunnableRetry({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields, + }); } - return messagesCopy.slice(0, idx); -} -async function _lastMaxTokens(messages, options) { - const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; - // Create a copy of messages to avoid mutation - let messagesCopy = messages.map((message) => { - const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); - }); - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (messagesCopy.length > 0 && - !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) { - messagesCopy = messagesCopy.slice(0, -1); - } + async invoke(input, options) { + return this.bound.invoke(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); } - const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; - let reversed_ = swappedSystem - ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) - : messagesCopy.reverse(); - reversed_ = await _firstMaxTokens(reversed_, { - ...rest, - partialStrategy: allowPartial ? "last" : undefined, - endOn: startOn, - }); - if (swappedSystem) { - return [reversed_[0], ...reversed_.slice(1).reverse()]; + async batch(inputs, options, batchOptions) { + const mergedOptions = Array.isArray(options) + ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) + : await this._mergeConfig(ensureConfig(options), this.kwargs); + return this.bound.batch(inputs, mergedOptions, batchOptions); } - else { - return reversed_.reverse(); + async *_streamIterator(input, options) { + yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); } -} -const _MSG_CHUNK_MAP = { - human: { - message: human_HumanMessage, - messageChunk: human_HumanMessageChunk, - }, - ai: { - message: ai_AIMessage, - messageChunk: ai_AIMessageChunk, - }, - system: { - message: system_SystemMessage, - messageChunk: system_SystemMessageChunk, - }, - developer: { - message: system_SystemMessage, - messageChunk: system_SystemMessageChunk, - }, - tool: { - message: tool_ToolMessage, - messageChunk: tool_ToolMessageChunk, - }, - function: { - message: function_FunctionMessage, - messageChunk: function_FunctionMessageChunk, - }, - generic: { - message: chat_ChatMessage, - messageChunk: chat_ChatMessageChunk, - }, - remove: { - message: RemoveMessage, - messageChunk: RemoveMessage, // RemoveMessage does not have a chunk class. - }, -}; -function _switchTypeToMessage(messageType, fields, returnChunk) { - let chunk; - let msg; - switch (messageType) { - case "human": - if (returnChunk) { - chunk = new HumanMessageChunk(fields); - } - else { - msg = new HumanMessage(fields); - } - break; - case "ai": - if (returnChunk) { - let aiChunkFields = { - ...fields, - }; - if ("tool_calls" in aiChunkFields) { - aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: undefined, - args: JSON.stringify(tc.args), - })), - }; - } - chunk = new AIMessageChunk(aiChunkFields); - } - else { - msg = new AIMessage(fields); - } - break; - case "system": - if (returnChunk) { - chunk = new SystemMessageChunk(fields); - } - else { - msg = new SystemMessage(fields); - } - break; - case "developer": - if (returnChunk) { - chunk = new SystemMessageChunk({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer", - }, - }); - } - else { - msg = new SystemMessage({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer", - }, - }); - } - break; - case "tool": - if ("tool_call_id" in fields) { - if (returnChunk) { - chunk = new ToolMessageChunk(fields); - } - else { - msg = new ToolMessage(fields); - } - } - else { - throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); - } - break; - case "function": - if (returnChunk) { - chunk = new FunctionMessageChunk(fields); - } - else { - if (!fields.name) { - throw new Error("FunctionMessage must have a 'name' field"); - } - msg = new FunctionMessage(fields); - } - break; - case "generic": - if ("role" in fields) { - if (returnChunk) { - chunk = new ChatMessageChunk(fields); - } - else { - msg = new ChatMessage(fields); - } - } - else { - throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); - } - break; - default: - throw new Error(`Unrecognized message type ${messageType}`); + async stream(input, options) { + return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); } - if (returnChunk && chunk) { - return chunk; + async *transform(generator, options) { + yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); } - if (msg) { - return msg; + streamEvents(input, options, streamOptions) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const outerThis = this; + const generator = async function* () { + yield* outerThis.bound.streamEvents(input, { + ...(await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs)), + version: options.version, + }, streamOptions); + }; + return IterableReadableStream.fromAsyncGenerator(generator()); } - throw new Error(`Unrecognized message type ${messageType}`); -} -function _chunkToMsg(chunk) { - const chunkType = chunk.getType(); - let msg; - const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); - if (chunkType in _MSG_CHUNK_MAP) { - msg = _switchTypeToMessage(chunkType, fields); + static isRunnableBinding( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + thing + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ) { + return thing.bound && Runnable.isRunnable(thing.bound); } - if (!msg) { - throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError, }) { + return new RunnableBinding({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + configFactories: [ + (config) => ({ + callbacks: [ + new RootListenersTracer({ + config, + onStart, + onEnd, + onError, + }), + ], + }), + ], + }); } - return msg; } /** - * The default text splitter function that splits text by newlines. + * A runnable that delegates calls to another runnable + * with each element of the input sequence. + * @example + * ```typescript + * import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; * - * @param {string} text - * @returns A promise that resolves to an array of strings split by newlines. + * const toUpperCase = (input: string): string => input.toUpperCase(); + * const addGreeting = (input: string): string => `Hello, ${input}!`; + * + * const upperCaseLambda = RunnableLambda.from(toUpperCase); + * const greetingLambda = RunnableLambda.from(addGreeting); + * + * const chain = new RunnableEach({ + * bound: upperCaseLambda.pipe(greetingLambda), + * }); + * + * const result = await chain.invoke(["alice", "bob", "carol"]) + * + * // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] + * ``` + * + * @deprecated This will be removed in the next breaking release. */ -function defaultTextSplitter(text) { - const splits = text.split("\n"); - return Promise.resolve([ - ...splits.slice(0, -1).map((s) => `${s}\n`), - splits[splits.length - 1], - ]); +class RunnableEach extends Runnable { + static lc_name() { + return "RunnableEach"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "bound", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.bound = fields.bound; + } + /** + * Binds the runnable with the specified arguments. + * @param kwargs The arguments to bind the runnable with. + * @returns A new instance of the `RunnableEach` class that is bound with the specified arguments. + * + * @deprecated Use {@link withConfig} instead. This will be removed in the next breaking release. + */ + bind(kwargs) { + return new RunnableEach({ + bound: this.bound.bind(kwargs), + }); + } + /** + * Invokes the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(inputs, config) { + return this._callWithConfig(this._invoke.bind(this), inputs, config); + } + /** + * A helper method that is used to invoke the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async _invoke(inputs, config, runManager) { + return this.bound.batch(inputs, patchConfig(config, { callbacks: runManager?.getChild() })); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError, }) { + return new RunnableEach({ + bound: this.bound.withListeners({ onStart, onEnd, onError }), + }); + } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js - - - - - - - - - - -// TODO: Use a star export when we deprecate the -// existing "ToolCall" type in "base.js". - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/messages.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha1/hash.js -// @ts-nocheck -// Inlined to deal with portability issues with importing crypto module -/* - * [js-sha1]{@link https://github.com/emn178/js-sha1} +/** + * Base class for runnables that can be retried a + * specified number of times. + * @example + * ```typescript + * import { + * RunnableLambda, + * RunnableRetry, + * } from "@langchain/core/runnables"; * - * @version 0.6.0 - * @author Chen, Yi-Cyuan [emn178@gmail.com] - * @copyright Chen, Yi-Cyuan 2014-2017 - * @license MIT + * // Simulate an API call that fails + * const simulateApiCall = (input: string): string => { + * console.log(`Attempting API call with input: ${input}`); + * throw new Error("API call failed due to network issue"); + * }; + * + * const apiCallLambda = RunnableLambda.from(simulateApiCall); + * + * // Apply retry logic using the .withRetry() method + * const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); + * + * // Alternatively, create a RunnableRetry instance manually + * const manualRetry = new RunnableRetry({ + * bound: apiCallLambda, + * maxAttemptNumber: 3, + * config: {}, + * }); + * + * // Example invocation using the .withRetry() method + * const res = await apiCallWithRetry + * .invoke("Request 1") + * .catch((error) => { + * console.error("Failed after multiple retries:", error.message); + * }); + * + * // Example invocation using the manual retry instance + * const res2 = await manualRetry + * .invoke("Request 2") + * .catch((error) => { + * console.error("Failed after multiple retries:", error.message); + * }); + * ``` */ -/*jslint bitwise: true */ - -var root = typeof window === "object" ? window : {}; -var HEX_CHARS = "0123456789abcdef".split(""); -var EXTRA = [-2147483648, 8388608, 32768, 128]; -var SHIFT = [24, 16, 8, 0]; -var OUTPUT_TYPES = (/* unused pure expression or super */ null && (["hex", "array", "digest", "arrayBuffer"])); -var blocks = []; -function Sha1(sharedMemory) { - if (sharedMemory) { - blocks[0] = - blocks[16] = - blocks[1] = - blocks[2] = - blocks[3] = - blocks[4] = - blocks[5] = - blocks[6] = - blocks[7] = - blocks[8] = - blocks[9] = - blocks[10] = - blocks[11] = - blocks[12] = - blocks[13] = - blocks[14] = - blocks[15] = - 0; - this.blocks = blocks; +class RunnableRetry extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "maxAttemptNumber", { + enumerable: true, + configurable: true, + writable: true, + value: 3 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "onFailedAttempt", { + enumerable: true, + configurable: true, + writable: true, + value: () => { } + }); + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; + } + _patchConfigForRetry(attempt, config, runManager) { + const tag = attempt > 1 ? `retry:attempt:${attempt}` : undefined; + return patchConfig(config, { callbacks: runManager?.getChild(tag) }); + } + async _invoke(input, config, runManager) { + return p_retry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onFailedAttempt: (error) => this.onFailedAttempt(error, input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true, + }); + } + /** + * Method that invokes the runnable with the specified input, run manager, + * and config. It handles the retry logic by catching any errors and + * recursively invoking itself with the updated config for the next retry + * attempt. + * @param input The input for the runnable. + * @param runManager The run manager for the runnable. + * @param config The config for the runnable. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(input, config) { + return this._callWithConfig(this._invoke.bind(this), input, config); + } + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await p_retry(async (attemptNumber) => { + const remainingIndexes = inputs + .map((_, i) => i) + .filter((i) => resultsMap[i.toString()] === undefined || + // eslint-disable-next-line no-instanceof/no-instanceof + resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true, + }); + let firstException; + for (let i = 0; i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + // eslint-disable-next-line no-instanceof/no-instanceof + if (result instanceof Error) { + if (firstException === undefined) { + firstException = result; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + firstException.input = remainingInputs[i]; + } + } + resultsMap[resultMapIndex.toString()] = result; + } + if (firstException) { + throw firstException; + } + return results; + }, { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onFailedAttempt: (error) => this.onFailedAttempt(error, error.input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true, + }); + } + catch (e) { + if (batchOptions?.returnExceptions !== true) { + throw e; + } + } + return Object.keys(resultsMap) + .sort((a, b) => parseInt(a, 10) - parseInt(b, 10)) + .map((key) => resultsMap[parseInt(key, 10)]); } - else { - this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); } - this.h0 = 0x67452301; - this.h1 = 0xefcdab89; - this.h2 = 0x98badcfe; - this.h3 = 0x10325476; - this.h4 = 0xc3d2e1f0; - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; } -Sha1.prototype.update = function (message) { - if (this.finalized) { - return; +/** + * A sequence of runnables, where the output of each is the input of the next. + * @example + * ```typescript + * const promptTemplate = PromptTemplate.fromTemplate( + * "Tell me a joke about {topic}", + * ); + * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]); + * const result = await chain.invoke({ topic: "bears" }); + * ``` + */ +class RunnableSequence extends Runnable { + static lc_name() { + return "RunnableSequence"; } - var notString = typeof message !== "string"; - if (notString && message.constructor === root.ArrayBuffer) { - message = new Uint8Array(message); + constructor(fields) { + super(fields); + Object.defineProperty(this, "first", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "middle", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "last", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "omitSequenceTags", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + this.name = fields.name; + this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; } - var code, index = 0, i, length = message.length || 0, blocks = this.blocks; - while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks[0] = this.block; - blocks[16] = - blocks[1] = - blocks[2] = - blocks[3] = - blocks[4] = - blocks[5] = - blocks[6] = - blocks[7] = - blocks[8] = - blocks[9] = - blocks[10] = - blocks[11] = - blocks[12] = - blocks[13] = - blocks[14] = - blocks[15] = - 0; - } - if (notString) { - for (i = this.start; index < length && i < 64; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + get steps() { + return [this.first, ...this.middle, this.last]; + } + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, undefined, undefined, undefined, config?.runName); + delete config.runId; + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) { + const step = initialSteps[i]; + const promise = step.invoke(nextStepInput, patchConfig(config, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), + })); + nextStepInput = await raceWithSignal(promise, options?.signal); } - } - else { - for (i = this.start; index < length && i < 64; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } - else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - else { - code = - 0x10000 + - (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); - blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } + // TypeScript can't detect that the last output of the sequence returns RunOutput, so call it out of the loop here + if (options?.signal?.aborted) { + throw new Error("Aborted"); } + finalOutput = await this.last.invoke(nextStepInput, patchConfig(config, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${this.steps.length}`), + })); } - this.lastByteIndex = i; - this.bytes += i - this.start; - if (i >= 64) { - this.block = blocks[16]; - this.start = i - 64; - this.hash(); - this.hashed = true; - } - else { - this.start = i; + catch (e) { + await runManager?.handleChainError(e); + throw e; } + await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); + return finalOutput; } - if (this.bytes > 4294967295) { - this.hBytes += (this.bytes / 4294967296) << 0; - this.bytes = this.bytes % 4294967296; - } - return this; -}; -Sha1.prototype.finalize = function () { - if (this.finalized) { - return; - } - this.finalized = true; - var blocks = this.blocks, i = this.lastByteIndex; - blocks[16] = this.block; - blocks[i >> 2] |= EXTRA[i & 3]; - this.block = blocks[16]; - if (i >= 56) { - if (!this.hashed) { - this.hash(); + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let nextStepInputs = inputs; + try { + for (let i = 0; i < this.steps.length; i += 1) { + const step = this.steps[i]; + const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { + const childRunManager = runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`); + return patchConfig(configList[j], { callbacks: childRunManager }); + }), batchOptions); + nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); + } } - blocks[0] = this.block; - blocks[16] = - blocks[1] = - blocks[2] = - blocks[3] = - blocks[4] = - blocks[5] = - blocks[6] = - blocks[7] = - blocks[8] = - blocks[9] = - blocks[10] = - blocks[11] = - blocks[12] = - blocks[13] = - blocks[14] = - blocks[15] = - 0; - } - blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); - blocks[15] = this.bytes << 3; - this.hash(); -}; -Sha1.prototype.hash = function () { - var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; - var f, j, t, blocks = this.blocks; - for (j = 16; j < 80; ++j) { - t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; - blocks[j] = (t << 1) | (t >>> 31); - } - for (j = 0; j < 20; j += 5) { - f = (b & c) | (~b & d); - t = (a << 5) | (a >>> 27); - e = (t + f + e + 1518500249 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = (a & b) | (~a & c); - t = (e << 5) | (e >>> 27); - d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = (e & a) | (~e & b); - t = (d << 5) | (d >>> 27); - c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = (d & e) | (~d & a); - t = (c << 5) | (c >>> 27); - b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = (c & d) | (~c & e); - t = (b << 5) | (b >>> 27); - a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - for (; j < 40; j += 5) { - f = b ^ c ^ d; - t = (a << 5) | (a >>> 27); - e = (t + f + e + 1859775393 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = a ^ b ^ c; - t = (e << 5) | (e >>> 27); - d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = e ^ a ^ b; - t = (d << 5) | (d >>> 27); - c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = d ^ e ^ a; - t = (c << 5) | (c >>> 27); - b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = c ^ d ^ e; - t = (b << 5) | (b >>> 27); - a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - for (; j < 60; j += 5) { - f = (b & c) | (b & d) | (c & d); - t = (a << 5) | (a >>> 27); - e = (t + f + e - 1894007588 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = (a & b) | (a & c) | (b & c); - t = (e << 5) | (e >>> 27); - d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = (e & a) | (e & b) | (a & b); - t = (d << 5) | (d >>> 27); - c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = (d & e) | (d & a) | (e & a); - t = (c << 5) | (c >>> 27); - b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = (c & d) | (c & e) | (d & e); - t = (b << 5) | (b >>> 27); - a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); - } - for (; j < 80; j += 5) { - f = b ^ c ^ d; - t = (a << 5) | (a >>> 27); - e = (t + f + e - 899497514 + blocks[j]) << 0; - b = (b << 30) | (b >>> 2); - f = a ^ b ^ c; - t = (e << 5) | (e >>> 27); - d = (t + f + d - 899497514 + blocks[j + 1]) << 0; - a = (a << 30) | (a >>> 2); - f = e ^ a ^ b; - t = (d << 5) | (d >>> 27); - c = (t + f + c - 899497514 + blocks[j + 2]) << 0; - e = (e << 30) | (e >>> 2); - f = d ^ e ^ a; - t = (c << 5) | (c >>> 27); - b = (t + f + b - 899497514 + blocks[j + 3]) << 0; - d = (d << 30) | (d >>> 2); - f = c ^ d ^ e; - t = (b << 5) | (b >>> 27); - a = (t + f + a - 899497514 + blocks[j + 4]) << 0; - c = (c << 30) | (c >>> 2); + catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); + return nextStepInputs; } - this.h0 = (this.h0 + a) << 0; - this.h1 = (this.h1 + b) << 0; - this.h2 = (this.h2 + c) << 0; - this.h3 = (this.h3 + d) << 0; - this.h4 = (this.h4 + e) << 0; -}; -Sha1.prototype.hex = function () { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; - return (HEX_CHARS[(h0 >> 28) & 0x0f] + - HEX_CHARS[(h0 >> 24) & 0x0f] + - HEX_CHARS[(h0 >> 20) & 0x0f] + - HEX_CHARS[(h0 >> 16) & 0x0f] + - HEX_CHARS[(h0 >> 12) & 0x0f] + - HEX_CHARS[(h0 >> 8) & 0x0f] + - HEX_CHARS[(h0 >> 4) & 0x0f] + - HEX_CHARS[h0 & 0x0f] + - HEX_CHARS[(h1 >> 28) & 0x0f] + - HEX_CHARS[(h1 >> 24) & 0x0f] + - HEX_CHARS[(h1 >> 20) & 0x0f] + - HEX_CHARS[(h1 >> 16) & 0x0f] + - HEX_CHARS[(h1 >> 12) & 0x0f] + - HEX_CHARS[(h1 >> 8) & 0x0f] + - HEX_CHARS[(h1 >> 4) & 0x0f] + - HEX_CHARS[h1 & 0x0f] + - HEX_CHARS[(h2 >> 28) & 0x0f] + - HEX_CHARS[(h2 >> 24) & 0x0f] + - HEX_CHARS[(h2 >> 20) & 0x0f] + - HEX_CHARS[(h2 >> 16) & 0x0f] + - HEX_CHARS[(h2 >> 12) & 0x0f] + - HEX_CHARS[(h2 >> 8) & 0x0f] + - HEX_CHARS[(h2 >> 4) & 0x0f] + - HEX_CHARS[h2 & 0x0f] + - HEX_CHARS[(h3 >> 28) & 0x0f] + - HEX_CHARS[(h3 >> 24) & 0x0f] + - HEX_CHARS[(h3 >> 20) & 0x0f] + - HEX_CHARS[(h3 >> 16) & 0x0f] + - HEX_CHARS[(h3 >> 12) & 0x0f] + - HEX_CHARS[(h3 >> 8) & 0x0f] + - HEX_CHARS[(h3 >> 4) & 0x0f] + - HEX_CHARS[h3 & 0x0f] + - HEX_CHARS[(h4 >> 28) & 0x0f] + - HEX_CHARS[(h4 >> 24) & 0x0f] + - HEX_CHARS[(h4 >> 20) & 0x0f] + - HEX_CHARS[(h4 >> 16) & 0x0f] + - HEX_CHARS[(h4 >> 12) & 0x0f] + - HEX_CHARS[(h4 >> 8) & 0x0f] + - HEX_CHARS[(h4 >> 4) & 0x0f] + - HEX_CHARS[h4 & 0x0f]); -}; -Sha1.prototype.toString = Sha1.prototype.hex; -Sha1.prototype.digest = function () { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; - return [ - (h0 >> 24) & 0xff, - (h0 >> 16) & 0xff, - (h0 >> 8) & 0xff, - h0 & 0xff, - (h1 >> 24) & 0xff, - (h1 >> 16) & 0xff, - (h1 >> 8) & 0xff, - h1 & 0xff, - (h2 >> 24) & 0xff, - (h2 >> 16) & 0xff, - (h2 >> 8) & 0xff, - h2 & 0xff, - (h3 >> 24) & 0xff, - (h3 >> 16) & 0xff, - (h3 >> 8) & 0xff, - h3 & 0xff, - (h4 >> 24) & 0xff, - (h4 >> 16) & 0xff, - (h4 >> 8) & 0xff, - h4 & 0xff, - ]; -}; -Sha1.prototype.array = Sha1.prototype.digest; -Sha1.prototype.arrayBuffer = function () { - this.finalize(); - var buffer = new ArrayBuffer(20); - var dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - return buffer; -}; -const insecureHash = (message) => { - return new Sha1(true).update(message)["hex"](); -}; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/base.js - - -/** - * This cache key should be consistent across all versions of LangChain. - * It is currently NOT consistent across versions of LangChain. - * - * A huge benefit of having a remote cache (like redis) is that you can - * access the cache from different processes/machines. The allows you to - * separate concerns and scale horizontally. - * - * TODO: Make cache key consistent across versions of LangChain. - */ -const getCacheKey = (...strings) => insecureHash(strings.join("_")); -function deserializeStoredGeneration(storedGeneration) { - if (storedGeneration.message !== undefined) { - return { - text: storedGeneration.text, - message: mapStoredMessageToChatMessage(storedGeneration.message), - }; + async *_streamIterator(input, options) { + const callbackManager_ = await getCallbackManagerForConfig(options); + const { runId, ...otherOptions } = options ?? {}; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherOptions?.runName); + const steps = [this.first, ...this.middle, this.last]; + let concatSupported = true; + let finalOutput; + async function* inputGenerator() { + yield input; + } + try { + let finalGenerator = steps[0].transform(inputGenerator(), patchConfig(otherOptions, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:1`), + })); + for (let i = 1; i < steps.length; i += 1) { + const step = steps[i]; + finalGenerator = await step.transform(finalGenerator, patchConfig(otherOptions, { + callbacks: runManager?.getChild(this.omitSequenceTags ? undefined : `seq:step:${i + 1}`), + })); + } + for await (const chunk of finalGenerator) { + options?.signal?.throwIfAborted(); + yield chunk; + if (concatSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = undefined; + concatSupported = false; + } + } + } + } + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); } - else { - return { text: storedGeneration.text }; + getGraph(config) { + const graph = new Graph(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let currentLastNode = null; + this.steps.forEach((step, index) => { + const stepGraph = step.getGraph(config); + if (index !== 0) { + stepGraph.trimFirstNode(); + } + if (index !== this.steps.length - 1) { + stepGraph.trimLastNode(); + } + graph.extend(stepGraph); + const stepFirstNode = stepGraph.firstNode(); + if (!stepFirstNode) { + throw new Error(`Runnable ${step} has no first node`); + } + if (currentLastNode) { + graph.addEdge(currentLastNode, stepFirstNode); + } + currentLastNode = stepGraph.lastNode(); + }); + return graph; } -} -function serializeGeneration(generation) { - const serializedValue = { - text: generation.text, - }; - if (generation.message !== undefined) { - serializedValue.message = generation.message.toDict(); + pipe(coerceable) { + if (RunnableSequence.isRunnableSequence(coerceable)) { + return new RunnableSequence({ + first: this.first, + middle: this.middle.concat([ + this.last, + coerceable.first, + ...coerceable.middle, + ]), + last: coerceable.last, + name: this.name ?? coerceable.name, + }); + } + else { + return new RunnableSequence({ + first: this.first, + middle: [...this.middle, this.last], + last: _coerceToRunnable(coerceable), + name: this.name, + }); + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static isRunnableSequence(thing) { + return Array.isArray(thing.middle) && Runnable.isRunnable(thing); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from([first, ...runnables], nameOrFields) { + let extra = {}; + if (typeof nameOrFields === "string") { + extra.name = nameOrFields; + } + else if (nameOrFields !== undefined) { + extra = nameOrFields; + } + return new RunnableSequence({ + ...extra, + first: _coerceToRunnable(first), + middle: runnables.slice(0, -1).map(_coerceToRunnable), + last: _coerceToRunnable(runnables[runnables.length - 1]), + }); } - return serializedValue; -} -/** - * Base class for all caches. All caches should extend this class. - */ -class BaseCache { } -const GLOBAL_MAP = new Map(); /** - * A cache for storing LLM generations that stores data in memory. + * A runnable that runs a mapping of runnables in parallel, + * and returns a mapping of their outputs. + * @example + * ```typescript + * const mapChain = RunnableMap.from({ + * joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( + * new ChatAnthropic({}), + * ), + * poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( + * new ChatAnthropic({}), + * ), + * }); + * const result = await mapChain.invoke({ topic: "bear" }); + * ``` */ -class InMemoryCache extends BaseCache { - constructor(map) { - super(); - Object.defineProperty(this, "cache", { +class RunnableMap extends Runnable { + static lc_name() { + return "RunnableMap"; + } + getStepsKeys() { + return Object.keys(this.steps); + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "steps", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.cache = map ?? new Map(); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) { + this.steps[key] = _coerceToRunnable(value); + } } - /** - * Retrieves data from the cache using a prompt and an LLM key. If the - * data is not found, it returns null. - * @param prompt The prompt used to find the data. - * @param llmKey The LLM key used to find the data. - * @returns The data corresponding to the prompt and LLM key, or null if not found. - */ - lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); + static from(steps) { + return new RunnableMap({ steps }); } - /** - * Updates the cache with new data using a prompt and an LLM key. - * @param prompt The prompt used to store the data. - * @param llmKey The LLM key used to store the data. - * @param value The data to be stored. - */ - async update(prompt, llmKey, value) { - this.cache.set(getCacheKey(prompt, llmKey), value); + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { + input, + }, config.runId, undefined, undefined, undefined, config?.runName); + delete config.runId; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const output = {}; + try { + const promises = Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`map:key:${key}`), + })); + }); + await raceWithSignal(Promise.all(promises), options?.signal); + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; } - /** - * Returns a global instance of InMemoryCache using a predefined global - * map as the initial cache. - * @returns A global instance of InMemoryCache. - */ - static global() { - return new InMemoryCache(GLOBAL_MAP); + async *_transform(generator, runManager, options) { + // shallow copy steps to ignore changes while iterating + const steps = { ...this.steps }; + // each step gets a copy of the input iterator + const inputCopies = atee(generator, Object.keys(steps).length); + // start the first iteration of each output iterator + const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { + const gen = runnable.transform(inputCopies[i], patchConfig(options, { + callbacks: runManager?.getChild(`map:key:${key}`), + })); + return [key, gen.next().then((result) => ({ key, gen, result }))]; + })); + // yield chunks as they become available, + // starting new iterations as needed, + // until all iterators are done + while (tasks.size) { + const promise = Promise.race(tasks.values()); + const { key, result, gen } = await raceWithSignal(promise, options?.signal); + tasks.delete(key); + if (!result.done) { + yield { [key]: result.value }; + tasks.set(key, gen.next().then((result) => ({ key, gen, result }))); + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js - - - -/** - * Base PromptValue class. All prompt values should extend this class. - */ -class BasePromptValue extends Serializable { } /** - * Represents a prompt value as a string. It extends the BasePromptValue - * class and overrides the toString and toChatMessages methods. + * A runnable that wraps a traced LangSmith function. */ -class StringPromptValue extends BasePromptValue { - static lc_name() { - return "StringPromptValue"; - } - constructor(value) { - super({ value }); - Object.defineProperty(this, "lc_namespace", { +class RunnableTraceable extends Runnable { + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "prompt_values"] + value: false }); - Object.defineProperty(this, "lc_serializable", { + Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: true + value: ["langchain_core", "runnables"] }); - Object.defineProperty(this, "value", { + Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.value = value; + if (!isTraceableFunction(fields.func)) { + throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + } + this.func = fields.func; } - toString() { - return this.value; + async invoke(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const callbacks = await getCallbackManagerForConfig(config); + const promise = this.func(patchConfig(config, { callbacks }), input); + return raceWithSignal(promise, config?.signal); } - toChatMessages() { - return [new human_HumanMessage(this.value)]; + async *_streamIterator(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const result = await this.invoke(input, options); + if (iter_isAsyncIterable(result)) { + for await (const item of result) { + config?.signal?.throwIfAborted(); + yield item; + } + return; + } + if (isIterator(result)) { + while (true) { + config?.signal?.throwIfAborted(); + const state = result.next(); + if (state.done) + break; + yield state.value; + } + return; + } + yield result; + } + static from(func) { + return new RunnableTraceable({ func }); + } +} +function assertNonTraceableFunction(func) { + if (isTraceableFunction(func)) { + throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); } } /** - * Class that represents a chat prompt value. It extends the - * BasePromptValue and includes an array of BaseMessage instances. + * A runnable that wraps an arbitrary function that takes a single argument. + * @example + * ```typescript + * import { RunnableLambda } from "@langchain/core/runnables"; + * + * const add = (input: { x: number; y: number }) => input.x + input.y; + * + * const multiply = (input: { value: number; multiplier: number }) => + * input.value * input.multiplier; + * + * // Create runnables for the functions + * const addLambda = RunnableLambda.from(add); + * const multiplyLambda = RunnableLambda.from(multiply); + * + * // Chain the lambdas for a mathematical operation + * const chainedLambda = addLambda.pipe((result) => + * multiplyLambda.invoke({ value: result, multiplier: 2 }) + * ); + * + * // Example invocation of the chainedLambda + * const result = await chainedLambda.invoke({ x: 2, y: 3 }); + * + * // Will log "10" (since (2 + 3) * 2 = 10) + * ``` */ -class ChatPromptValue extends BasePromptValue { +class base_RunnableLambda extends Runnable { static lc_name() { - return "ChatPromptValue"; + return "RunnableLambda"; } constructor(fields) { - if (Array.isArray(fields)) { - // eslint-disable-next-line no-param-reassign - fields = { messages: fields }; + if (isTraceableFunction(fields.func)) { + // eslint-disable-next-line no-constructor-return + return RunnableTraceable.from(fields.func); } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "prompt_values"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true + value: ["langchain_core", "runnables"] }); - Object.defineProperty(this, "messages", { + Object.defineProperty(this, "func", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.messages = fields.messages; + assertNonTraceableFunction(fields.func); + this.func = fields.func; } - toString() { - return getBufferString(this.messages); + static from(func) { + return new base_RunnableLambda({ + func, + }); } - toChatMessages() { - return this.messages; + async _invoke(input, config, runManager) { + return new Promise((resolve, reject) => { + const childConfig = patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }); + void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + let output = await this.func(input, { + ...childConfig, + }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) { + throw new Error("Recursion limit reached."); + } + output = await output.invoke(input, { + ...childConfig, + recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }); + } + else if (iter_isAsyncIterable(output)) { + let finalOutput; + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = chunk; + } + } + } + output = finalOutput; + } + else if (isIterableIterator(output)) { + let finalOutput; + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = chunk; + } + } + } + output = finalOutput; + } + resolve(output); + } + catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + return this._callWithConfig(this._invoke.bind(this), input, options); + } + async *_transform(generator, runManager, config) { + let finalChunk; + for await (const chunk of generator) { + if (finalChunk === undefined) { + finalChunk = chunk; + } + else { + // Make a best effort to gather, for any type that supports concat. + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalChunk = concat(finalChunk, chunk); + } + catch (e) { + finalChunk = chunk; + } + } + } + const childConfig = patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1, + }); + const output = await new Promise((resolve, reject) => { + void async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + const res = await this.func(finalChunk, { + ...childConfig, + config: childConfig, + }); + resolve(res); + } + catch (e) { + reject(e); + } + }); + }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) { + throw new Error("Recursion limit reached."); + } + const stream = await output.stream(finalChunk, childConfig); + for await (const chunk of stream) { + yield chunk; + } + } + else if (iter_isAsyncIterable(output)) { + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + } + else if (isIterableIterator(output)) { + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + } + else { + yield output; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +} +/** + * A runnable that runs a mapping of runnables in parallel, + * and returns a mapping of their outputs. + * @example + * ```typescript + * import { + * RunnableLambda, + * RunnableParallel, + * } from "@langchain/core/runnables"; + * + * const addYears = (age: number): number => age + 5; + * const yearsToFifty = (age: number): number => 50 - age; + * const yearsToHundred = (age: number): number => 100 - age; + * + * const addYearsLambda = RunnableLambda.from(addYears); + * const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); + * const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); + * + * // Pipe will coerce objects into RunnableParallel by default, but we + * // explicitly instantiate one here to demonstrate + * const sequence = addYearsLambda.pipe( + * RunnableParallel.from({ + * years_to_fifty: milestoneFiftyLambda, + * years_to_hundred: milestoneHundredLambda, + * }) + * ); + * + * // Invoke the sequence with a single age input + * const res = sequence.invoke(25); + * + * // { years_to_fifty: 25, years_to_hundred: 75 } + * ``` + */ +class RunnableParallel extends (/* unused pure expression or super */ null && (RunnableMap)) { } /** - * Class that represents an image prompt value. It extends the - * BasePromptValue and includes an ImageURL instance. + * A Runnable that can fallback to other Runnables if it fails. + * External APIs (e.g., APIs for a language model) may at times experience + * degraded performance or even downtime. + * + * In these cases, it can be useful to have a fallback Runnable that can be + * used in place of the original Runnable (e.g., fallback to another LLM provider). + * + * Fallbacks can be defined at the level of a single Runnable, or at the level + * of a chain of Runnables. Fallbacks are tried in order until one succeeds or + * all fail. + * + * While you can instantiate a `RunnableWithFallbacks` directly, it is usually + * more convenient to use the `withFallbacks` method on an existing Runnable. + * + * When streaming, fallbacks will only be called on failures during the initial + * stream creation. Errors that occur after a stream starts will not fallback + * to the next Runnable. + * + * @example + * ```typescript + * import { + * RunnableLambda, + * RunnableWithFallbacks, + * } from "@langchain/core/runnables"; + * + * const primaryOperation = (input: string): string => { + * if (input !== "safe") { + * throw new Error("Primary operation failed due to unsafe input"); + * } + * return `Processed: ${input}`; + * }; + * + * // Define a fallback operation that processes the input differently + * const fallbackOperation = (input: string): string => + * `Fallback processed: ${input}`; + * + * const primaryRunnable = RunnableLambda.from(primaryOperation); + * const fallbackRunnable = RunnableLambda.from(fallbackOperation); + * + * // Apply the fallback logic using the .withFallbacks() method + * const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); + * + * // Alternatively, create a RunnableWithFallbacks instance manually + * const manualFallbackChain = new RunnableWithFallbacks({ + * runnable: primaryRunnable, + * fallbacks: [fallbackRunnable], + * }); + * + * // Example invocation using .withFallbacks() + * const res = await runnableWithFallback + * .invoke("unsafe input") + * .catch((error) => { + * console.error("Failed after all attempts:", error.message); + * }); + * + * // "Fallback processed: unsafe input" + * + * // Example invocation using manual instantiation + * const res = await manualFallbackChain + * .invoke("safe") + * .catch((error) => { + * console.error("Failed after all attempts:", error.message); + * }); + * + * // "Processed: safe" + * ``` */ -class ImagePromptValue extends BasePromptValue { +class RunnableWithFallbacks extends Runnable { static lc_name() { - return "ImagePromptValue"; + return "RunnableWithFallbacks"; } constructor(fields) { - if (!("imageUrl" in fields)) { - // eslint-disable-next-line no-param-reassign - fields = { imageUrl: fields }; - } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "prompt_values"] + value: ["langchain_core", "runnables"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, @@ -101720,753 +111668,933 @@ class ImagePromptValue extends BasePromptValue { writable: true, value: true }); - Object.defineProperty(this, "imageUrl", { + Object.defineProperty(this, "runnable", { enumerable: true, configurable: true, writable: true, value: void 0 }); - /** @ignore */ - Object.defineProperty(this, "value", { + Object.defineProperty(this, "fallbacks", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.imageUrl = fields.imageUrl; - } - toString() { - return this.imageUrl.url; - } - toChatMessages() { - return [ - new human_HumanMessage({ - content: [ - { - type: "image_url", - image_url: { - detail: this.imageUrl.detail, - url: this.imageUrl.url, - }, - }, - ], - }), - ]; - } -} - -// EXTERNAL MODULE: ./node_modules/base64-js/index.js -var base64_js = __nccwpck_require__(8793); -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-YVJR5WRT.js - - -var __defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; - -// src/utils.ts -function never(_) { -} -function bytePairMerge(piece, ranks) { - let parts = Array.from( - { length: piece.length }, - (_, i) => ({ start: i, end: i + 1 }) - ); - while (parts.length > 1) { - let minRank = null; - for (let i = 0; i < parts.length - 1; i++) { - const slice = piece.slice(parts[i].start, parts[i + 1].end); - const rank = ranks.get(slice.join(",")); - if (rank == null) - continue; - if (minRank == null || rank < minRank[0]) { - minRank = [rank, i]; - } - } - if (minRank != null) { - const i = minRank[1]; - parts[i] = { start: parts[i].start, end: parts[i + 1].end }; - parts.splice(i + 1, 1); - } else { - break; - } - } - return parts; -} -function bytePairEncode(piece, ranks) { - if (piece.length === 1) - return [ranks.get(piece.join(","))]; - return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); -} -function escapeRegex(str) { - return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); -} -var _Tiktoken = class { - /** @internal */ - specialTokens; - /** @internal */ - inverseSpecialTokens; - /** @internal */ - patStr; - /** @internal */ - textEncoder = new TextEncoder(); - /** @internal */ - textDecoder = new TextDecoder("utf-8"); - /** @internal */ - rankMap = /* @__PURE__ */ new Map(); - /** @internal */ - textMap = /* @__PURE__ */ new Map(); - constructor(ranks, extendedSpecialTokens) { - this.patStr = ranks.pat_str; - const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { - const [_, offsetStr, ...tokens] = x.split(" "); - const offset = Number.parseInt(offsetStr, 10); - tokens.forEach((token, i) => memo[token] = offset + i); - return memo; - }, {}); - for (const [token, rank] of Object.entries(uncompressed)) { - const bytes = base64_js.toByteArray(token); - this.rankMap.set(bytes.join(","), rank); - this.textMap.set(rank, bytes); - } - this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; - this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { - memo[rank] = this.textEncoder.encode(text); - return memo; - }, {}); - } - encode(text, allowedSpecial = [], disallowedSpecial = "all") { - const regexes = new RegExp(this.patStr, "ug"); - const specialRegex = _Tiktoken.specialTokenRegex( - Object.keys(this.specialTokens) - ); - const ret = []; - const allowedSpecialSet = new Set( - allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial - ); - const disallowedSpecialSet = new Set( - disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( - (x) => !allowedSpecialSet.has(x) - ) : disallowedSpecial - ); - if (disallowedSpecialSet.size > 0) { - const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ - ...disallowedSpecialSet - ]); - const specialMatch = text.match(disallowedSpecialRegex); - if (specialMatch != null) { - throw new Error( - `The text contains a special token that is not allowed: ${specialMatch[0]}` - ); - } + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; } - let start = 0; - while (true) { - let nextSpecial = null; - let startFind = start; - while (true) { - specialRegex.lastIndex = startFind; - nextSpecial = specialRegex.exec(text); - if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) - break; - startFind = nextSpecial.index + 1; - } - const end = nextSpecial?.index ?? text.length; - for (const match of text.substring(start, end).matchAll(regexes)) { - const piece = this.textEncoder.encode(match[0]); - const token2 = this.rankMap.get(piece.join(",")); - if (token2 != null) { - ret.push(token2); - continue; + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) { + yield fallback; } - ret.push(...bytePairEncode(piece, this.rankMap)); - } - if (nextSpecial == null) - break; - let token = this.specialTokens[nextSpecial[0]]; - ret.push(token); - start = nextSpecial.index + nextSpecial[0].length; - } - return ret; - } - decode(tokens) { - const res = []; - let length = 0; - for (let i2 = 0; i2 < tokens.length; ++i2) { - const token = tokens[i2]; - const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; - if (bytes != null) { - res.push(bytes); - length += bytes.length; - } - } - const mergedArray = new Uint8Array(length); - let i = 0; - for (const bytes of res) { - mergedArray.set(bytes, i); - i += bytes.length; - } - return this.textDecoder.decode(mergedArray); - } -}; -var Tiktoken = _Tiktoken; -__publicField(Tiktoken, "specialTokenRegex", (tokens) => { - return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g"); -}); -function getEncodingNameForModel(model) { - switch (model) { - case "gpt2": { - return "gpt2"; - } - case "code-cushman-001": - case "code-cushman-002": - case "code-davinci-001": - case "code-davinci-002": - case "cushman-codex": - case "davinci-codex": - case "davinci-002": - case "text-davinci-002": - case "text-davinci-003": { - return "p50k_base"; - } - case "code-davinci-edit-001": - case "text-davinci-edit-001": { - return "p50k_edit"; - } - case "ada": - case "babbage": - case "babbage-002": - case "code-search-ada-code-001": - case "code-search-babbage-code-001": - case "curie": - case "davinci": - case "text-ada-001": - case "text-babbage-001": - case "text-curie-001": - case "text-davinci-001": - case "text-search-ada-doc-001": - case "text-search-babbage-doc-001": - case "text-search-curie-doc-001": - case "text-search-davinci-doc-001": - case "text-similarity-ada-001": - case "text-similarity-babbage-001": - case "text-similarity-curie-001": - case "text-similarity-davinci-001": { - return "r50k_base"; - } - case "gpt-3.5-turbo-instruct-0914": - case "gpt-3.5-turbo-instruct": - case "gpt-3.5-turbo-16k-0613": - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo": - case "gpt-4-32k-0613": - case "gpt-4-32k-0314": - case "gpt-4-32k": - case "gpt-4-0613": - case "gpt-4-0314": - case "gpt-4": - case "gpt-3.5-turbo-1106": - case "gpt-35-turbo": - case "gpt-4-1106-preview": - case "gpt-4-vision-preview": - case "gpt-3.5-turbo-0125": - case "gpt-4-turbo": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-turbo-preview": - case "gpt-4-0125-preview": - case "text-embedding-ada-002": - case "text-embedding-3-small": - case "text-embedding-3-large": { - return "cl100k_base"; - } - case "gpt-4o": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": - case "gpt-4o-mini-2024-07-18": - case "gpt-4o-mini": - case "o1-mini": - case "o1-preview": - case "o1-preview-2024-09-12": - case "o1-mini-2024-09-12": - case "chatgpt-4o-latest": - case "gpt-4o-realtime": - case "gpt-4o-realtime-preview-2024-10-01": { - return "o200k_base"; } - default: - throw new Error("Unknown model"); - } -} - - - -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js - - -const cache = {}; -const caller = /* #__PURE__ */ new async_caller_AsyncCaller({}); -async function getEncoding(encoding) { - if (!(encoding in cache)) { - cache[encoding] = caller - .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`) - .then((res) => res.json()) - .then((data) => new Tiktoken(data)) - .catch((e) => { - delete cache[encoding]; - throw e; + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId, ...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); + const childConfig = patchConfig(otherConfigFields, { + callbacks: runManager?.getChild(), }); + const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { + let firstError; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + try { + const output = await runnable.invoke(input, childConfig); + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + return output; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (firstError === undefined) { + throw new Error("No error stored at end of fallback."); + } + await runManager?.handleChainError(firstError); + throw firstError; + }); + return res; } - return await cache[encoding]; -} -async function tiktoken_encodingForModel(model) { - return getEncoding(getEncodingNameForModel(model)); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js - - - - - - -// https://www.npmjs.com/package/js-tiktoken -const getModelNameForTiktoken = (modelName) => { - if (modelName.startsWith("gpt-3.5-turbo-16k")) { - return "gpt-3.5-turbo-16k"; - } - if (modelName.startsWith("gpt-3.5-turbo-")) { - return "gpt-3.5-turbo"; + async *_streamIterator(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId, ...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, undefined, undefined, undefined, otherConfigFields?.runName); + let firstError; + let stream; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + const childConfig = patchConfig(otherConfigFields, { + callbacks: runManager?.getChild(), + }); + try { + const originalStream = await runnable.stream(input, childConfig); + stream = consumeAsyncIterableInContext(childConfig, originalStream); + break; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (stream === undefined) { + const error = firstError ?? new Error("No error stored at end of fallback."); + await runManager?.handleChainError(error); + throw error; + } + let output; + try { + for await (const chunk of stream) { + yield chunk; + try { + output = output === undefined ? output : concat(output, chunk); + } + catch (e) { + output = undefined; + } + } + } + catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); } - if (modelName.startsWith("gpt-4-32k")) { - return "gpt-4-32k"; + async batch(inputs, options, batchOptions) { + if (batchOptions?.returnExceptions) { + throw new Error("Not implemented."); + } + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, undefined, undefined, undefined, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let firstError; + for (const runnable of this.runnables()) { + configList[0].signal?.throwIfAborted(); + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => patchConfig(configList[j], { + callbacks: runManager?.getChild(), + })), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); + return outputs; + } + catch (e) { + if (firstError === undefined) { + firstError = e; + } + } + } + if (!firstError) { + throw new Error("No error stored at end of fallbacks."); + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; } - if (modelName.startsWith("gpt-4-")) { - return "gpt-4"; +} +// TODO: Figure out why the compiler needs help eliminating Error as a RunOutput type +function _coerceToRunnable(coerceable) { + if (typeof coerceable === "function") { + return new base_RunnableLambda({ func: coerceable }); } - if (modelName.startsWith("gpt-4o")) { - return "gpt-4o"; + else if (Runnable.isRunnable(coerceable)) { + return coerceable; } - return modelName; -}; -const getEmbeddingContextSize = (modelName) => { - switch (modelName) { - case "text-embedding-ada-002": - return 8191; - default: - return 2046; + else if (!Array.isArray(coerceable) && typeof coerceable === "object") { + const runnables = {}; + for (const [key, value] of Object.entries(coerceable)) { + runnables[key] = _coerceToRunnable(value); + } + return new RunnableMap({ + steps: runnables, + }); } -}; -const getModelContextSize = (modelName) => { - switch (getModelNameForTiktoken(modelName)) { - case "gpt-3.5-turbo-16k": - return 16384; - case "gpt-3.5-turbo": - return 4096; - case "gpt-4-32k": - return 32768; - case "gpt-4": - return 8192; - case "text-davinci-003": - return 4097; - case "text-curie-001": - return 2048; - case "text-babbage-001": - return 2048; - case "text-ada-001": - return 2048; - case "code-davinci-002": - return 8000; - case "code-cushman-001": - return 2048; - default: - return 4097; + else { + throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); } -}; +} /** - * Whether or not the input matches the OpenAI tool definition. - * @param {unknown} tool The input to check. - * @returns {boolean} Whether the input is an OpenAI tool definition. + * A runnable that assigns key-value pairs to inputs of type `Record`. + * @example + * ```typescript + * import { + * RunnableAssign, + * RunnableLambda, + * RunnableParallel, + * } from "@langchain/core/runnables"; + * + * const calculateAge = (x: { birthYear: number }): { age: number } => { + * const currentYear = new Date().getFullYear(); + * return { age: currentYear - x.birthYear }; + * }; + * + * const createGreeting = (x: { name: string }): { greeting: string } => { + * return { greeting: `Hello, ${x.name}!` }; + * }; + * + * const mapper = RunnableParallel.from({ + * age_step: RunnableLambda.from(calculateAge), + * greeting_step: RunnableLambda.from(createGreeting), + * }); + * + * const runnableAssign = new RunnableAssign({ mapper }); + * + * const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); + * + * // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } + * ``` */ -function isOpenAITool(tool) { - if (typeof tool !== "object" || !tool) - return false; - if ("type" in tool && - tool.type === "function" && - "function" in tool && - typeof tool.function === "object" && - tool.function && - "name" in tool.function && - "parameters" in tool.function) { - return true; +class RunnableAssign extends Runnable { + static lc_name() { + return "RunnableAssign"; } - return false; -} -const calculateMaxTokens = async ({ prompt, modelName, }) => { - let numTokens; - try { - numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; + constructor(fields) { + // eslint-disable-next-line no-instanceof/no-instanceof + if (fields instanceof RunnableMap) { + // eslint-disable-next-line no-param-reassign + fields = { mapper: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "mapper", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.mapper = fields.mapper; } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count"); - // fallback to approximate calculation if tiktoken is not available - // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# - numTokens = Math.ceil(prompt.length / 4); + async invoke(input, options) { + const mapperResult = await this.mapper.invoke(input, options); + return { + ...input, + ...mapperResult, + }; } - const maxTokens = getModelContextSize(modelName); - return maxTokens - numTokens; -}; -const getVerbosity = () => false; + async *_transform(generator, runManager, options) { + // collect mapper keys + const mapperKeys = this.mapper.getStepsKeys(); + // create two input gens, one for the mapper, one for the input + const [forPassthrough, forMapper] = atee(generator); + // create mapper output gen + const mapperOutput = this.mapper.transform(forMapper, patchConfig(options, { callbacks: runManager?.getChild() })); + // start the mapper + const firstMapperChunkPromise = mapperOutput.next(); + // yield the passthrough + for await (const chunk of forPassthrough) { + if (typeof chunk !== "object" || Array.isArray(chunk)) { + throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); + } + const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); + if (Object.keys(filtered).length > 0) { + yield filtered; + } + } + // yield the mapper output + yield (await firstMapperChunkPromise).value; + for await (const chunk of mapperOutput) { + yield chunk; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +} /** - * Base class for language models, chains, tools. + * A runnable that assigns key-value pairs to inputs of type `Record`. + * Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. + * @example + * ```typescript + * import { RunnablePick } from "@langchain/core/runnables"; + * + * const inputData = { + * name: "John", + * age: 30, + * city: "New York", + * country: "USA", + * email: "john.doe@example.com", + * phone: "+1234567890", + * }; + * + * const basicInfoRunnable = new RunnablePick(["name", "city"]); + * + * // Example invocation + * const res = await basicInfoRunnable.invoke(inputData); + * + * // { name: 'John', city: 'New York' } + * ``` */ -class BaseLangChain extends Runnable { - get lc_attributes() { - return { - callbacks: undefined, - verbose: undefined, - }; +class RunnablePick extends Runnable { + static lc_name() { + return "RunnablePick"; } - constructor(params) { - super(params); - /** - * Whether to print out response text. - */ - Object.defineProperty(this, "verbose", { + constructor(fields) { + if (typeof fields === "string" || Array.isArray(fields)) { + // eslint-disable-next-line no-param-reassign + fields = { keys: fields }; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "keys", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "callbacks", { + this.keys = fields.keys; + } + async _pick(input) { + if (typeof this.keys === "string") { + return input[this.keys]; + } + else { + const picked = this.keys + .map((key) => [key, input[key]]) + .filter((v) => v[1] !== undefined); + return picked.length === 0 ? undefined : Object.fromEntries(picked); + } + } + async invoke(input, options) { + return this._callWithConfig(this._pick.bind(this), input, options); + } + async *_transform(generator) { + for await (const chunk of generator) { + const picked = await this._pick(chunk); + if (picked !== undefined) { + yield picked; + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config, + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +} +class RunnableToolLike extends RunnableBinding { + constructor(fields) { + const sequence = RunnableSequence.from([ + base_RunnableLambda.from(async (input) => { + let toolInput; + if (_isToolCall(input)) { + try { + toolInput = await interopParseAsync(this.schema, input.args); + } + catch (e) { + throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); + } + } + else { + toolInput = input; + } + return toolInput; + }).withConfig({ runName: `${fields.name}:parse_input` }), + fields.bound, + ]).withConfig({ runName: fields.name }); + super({ + bound: sequence, + config: fields.config ?? {}, + }); + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "tags", { + Object.defineProperty(this, "description", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "metadata", { + Object.defineProperty(this, "schema", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.verbose = params.verbose ?? getVerbosity(); - this.callbacks = params.callbacks; - this.tags = params.tags ?? []; - this.metadata = params.metadata ?? {}; + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + static lc_name() { + return "RunnableToolLike"; } } /** - * Base class for language models. + * Given a runnable and a Zod schema, convert the runnable to a tool. + * + * @template RunInput The input type for the runnable. + * @template RunOutput The output type for the runnable. + * + * @param {Runnable} runnable The runnable to convert to a tool. + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. */ -class BaseLanguageModel extends BaseLangChain { - /** - * Keys that the language model accepts as call options. - */ - get callKeys() { - return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; +function convertRunnableToTool(runnable, fields) { + const name = fields.name ?? runnable.getName(); + const description = fields.description ?? getSchemaDescription(fields.schema); + if (isSimpleStringZodSchema(fields.schema)) { + return new RunnableToolLike({ + name, + description, + schema: objectType({ input: stringType() }) + .transform((input) => input.input), + bound: runnable, + }); } - constructor({ callbacks, callbackManager, ...params }) { - const { cache, ...rest } = params; + return new RunnableToolLike({ + name, + description, + schema: fields.schema, + bound: runnable, + }); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js + +/** + * Message responsible for deleting other messages. + */ +class RemoveMessage extends BaseMessage { + constructor(fields) { super({ - callbacks: callbacks ?? callbackManager, - ...rest, + ...fields, + content: "", }); /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. + * The ID of the message to remove. */ - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cache", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_encoding", { + Object.defineProperty(this, "id", { enumerable: true, configurable: true, writable: true, value: void 0 }); - if (typeof cache === "object") { - this.cache = cache; + this.id = fields.id; + } + _getType() { + return "remove"; + } + get _printableFields() { + return { + ...super._printableFields, + id: this.id, + }; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js + + + + + + + + + + +const _isMessageType = (msg, types) => { + const typesAsStrings = [ + ...new Set(types?.map((t) => { + if (typeof t === "string") { + return t; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const instantiatedMsgClass = new t({}); + if (!("getType" in instantiatedMsgClass) || + typeof instantiatedMsgClass.getType !== "function") { + throw new Error("Invalid type provided."); + } + return instantiatedMsgClass.getType(); + })), + ]; + const msgType = msg.getType(); + return typesAsStrings.some((t) => t === msgType); +}; +function filterMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + return _filterMessages(messagesOrOptions, options); + } + return RunnableLambda.from((input) => { + return _filterMessages(input, messagesOrOptions); + }); +} +function _filterMessages(messages, options = {}) { + const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds, } = options; + const filtered = []; + for (const msg of messages) { + if (excludeNames && msg.name && excludeNames.includes(msg.name)) { + continue; } - else if (cache) { - this.cache = InMemoryCache.global(); + else if (excludeTypes && _isMessageType(msg, excludeTypes)) { + continue; } - else { - this.cache = undefined; + else if (excludeIds && msg.id && excludeIds.includes(msg.id)) { + continue; + } + // default to inclusion when no inclusion criteria given. + if (!(includeTypes || includeIds || includeNames)) { + filtered.push(msg); + } + else if (includeNames && + msg.name && + includeNames.some((iName) => iName === msg.name)) { + filtered.push(msg); + } + else if (includeTypes && _isMessageType(msg, includeTypes)) { + filtered.push(msg); + } + else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) { + filtered.push(msg); } - this.caller = new async_caller_AsyncCaller(params ?? {}); } - async getNumTokens(content) { - // TODO: Figure out correct value. - if (typeof content !== "string") { - return 0; + return filtered; +} +function mergeMessageRuns(messages) { + if (Array.isArray(messages)) { + return _mergeMessageRuns(messages); + } + return RunnableLambda.from(_mergeMessageRuns); +} +function _mergeMessageRuns(messages) { + if (!messages.length) { + return []; + } + const merged = []; + for (const msg of messages) { + const curr = msg; + const last = merged.pop(); + if (!last) { + merged.push(curr); } - // fallback to approximate calculation if tiktoken is not available - let numTokens = Math.ceil(content.length / 4); - if (!this._encoding) { - try { - this._encoding = await tiktoken_encodingForModel("modelName" in this - ? getModelNameForTiktoken(this.modelName) - : "gpt2"); - } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } + else if (curr.getType() === "tool" || + !(curr.getType() === last.getType())) { + merged.push(last, curr); } - if (this._encoding) { - try { - numTokens = this._encoding.encode(content).length; - } - catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + else { + const lastChunk = convertToChunk(last); + const currChunk = convertToChunk(curr); + const mergedChunks = lastChunk.concat(currChunk); + if (typeof lastChunk.content === "string" && + typeof currChunk.content === "string") { + mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; } + merged.push(_chunkToMsg(mergedChunks)); } - return numTokens; } - static _convertInputToPromptValue(input) { - if (typeof input === "string") { - return new StringPromptValue(input); - } - else if (Array.isArray(input)) { - return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); - } - else { - return input; + return merged; +} +function trimMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + const messages = messagesOrOptions; + if (!options) { + throw new Error("Options parameter is required when providing messages."); } + return _trimMessagesHelper(messages, options); } - /** - * Get the identifying parameters of the LLM. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _identifyingParams() { - return {}; + else { + const trimmerOptions = messagesOrOptions; + return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ + runName: "trim_messages", + }); } - /** - * Create a unique cache key for a specific call to a specific language model. - * @param callOptions Call options for the model - * @returns A unique cache key. - */ - _getSerializedCacheKeyParametersForCall( - // TODO: Fix when we remove the RunnableLambda backwards compatibility shim. - { config, ...callOptions }) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const params = { - ...this._identifyingParams(), - ...callOptions, - _type: this._llmType(), - _model: this._modelType(), - }; - const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); - const serializedEntries = filteredEntries - .map(([key, value]) => `${key}:${JSON.stringify(value)}`) - .sort() - .join(","); - return serializedEntries; +} +async function _trimMessagesHelper(messages, options) { + const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter, } = options; + if (startOn && strategy === "first") { + throw new Error("`startOn` should only be specified if `strategy` is 'last'."); } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType(), + if (includeSystem && strategy === "first") { + throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + } + let listTokenCounter; + if ("getNumTokens" in tokenCounter) { + listTokenCounter = async (msgs) => { + const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); + return tokenCounts.reduce((sum, count) => sum + count, 0); }; } - /** - * @deprecated - * Load an LLM from a json-like object describing it. - */ - static async deserialize(_data) { - throw new Error("Use .toJSON() instead"); + else { + listTokenCounter = async (msgs) => tokenCounter(msgs); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js - - - -/** - * A runnable to passthrough inputs unchanged or with additional keys. - * - * This runnable behaves almost like the identity function, except that it - * can be configured to add additional keys to the output, if the input is - * an object. - * - * The example below demonstrates how to use `RunnablePassthrough to - * passthrough the input from the `.invoke()` - * - * @example - * ```typescript - * const chain = RunnableSequence.from([ - * { - * question: new RunnablePassthrough(), - * context: async () => loadContextFromStore(), - * }, - * prompt, - * llm, - * outputParser, - * ]); - * const response = await chain.invoke( - * "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." - * ); - * ``` - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -class RunnablePassthrough extends Runnable { - static lc_name() { - return "RunnablePassthrough"; + let textSplitterFunc = defaultTextSplitter; + if (textSplitter) { + if ("splitText" in textSplitter) { + textSplitterFunc = textSplitter.splitText; + } + else { + textSplitterFunc = async (text) => textSplitter(text); + } } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain_core", "runnables"] - }); - Object.defineProperty(this, "lc_serializable", { - enumerable: true, - configurable: true, - writable: true, - value: true + if (strategy === "first") { + return _firstMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + partialStrategy: allowPartial ? "first" : undefined, + endOn, }); - Object.defineProperty(this, "func", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + } + else if (strategy === "last") { + return _lastMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + allowPartial, + includeSystem, + startOn, + endOn, }); - if (fields) { - this.func = fields.func; - } } - async invoke(input, options) { - const config = ensureConfig(options); - if (this.func) { - await this.func(input, config); + else { + throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); + } +} +async function _firstMaxTokens(messages, options) { + const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; + let messagesCopy = [...messages]; + let idx = 0; + for (let i = 0; i < messagesCopy.length; i += 1) { + const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; + if ((await tokenCounter(remainingMessages)) <= maxTokens) { + idx = messagesCopy.length - i; + break; } - return this._callWithConfig((input) => Promise.resolve(input), input, config); } - async *transform(generator, options) { - const config = ensureConfig(options); - let finalOutput; - let finalOutputSupported = true; - for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; + if (idx < messagesCopy.length - 1 && partialStrategy) { + let includedPartial = false; + if (Array.isArray(messagesCopy[idx].content)) { + const excluded = messagesCopy[idx]; + if (typeof excluded.content === "string") { + throw new Error("Expected content to be an array."); + } + const numBlock = excluded.content.length; + const reversedContent = partialStrategy === "last" + ? [...excluded.content].reverse() + : excluded.content; + for (let i = 1; i <= numBlock; i += 1) { + const partialContent = partialStrategy === "first" + ? reversedContent.slice(0, i) + : reversedContent.slice(-i); + const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + const updatedMessage = _switchTypeToMessage(excluded.getType(), { + ...fields, + content: partialContent, + }); + const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; + if ((await tokenCounter(slicedMessages)) <= maxTokens) { + messagesCopy = slicedMessages; + idx += 1; + includedPartial = true; } else { - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - finalOutput = concat(finalOutput, chunk); - } - catch { - finalOutput = undefined; - finalOutputSupported = false; + break; + } + } + if (includedPartial && partialStrategy === "last") { + excluded.content = [...reversedContent].reverse(); + } + } + if (!includedPartial) { + const excluded = messagesCopy[idx]; + let text; + if (Array.isArray(excluded.content) && + excluded.content.some((block) => typeof block === "string" || block.type === "text")) { + const textBlock = excluded.content.find((block) => block.type === "text" && block.text); + text = textBlock?.text; + } + else if (typeof excluded.content === "string") { + text = excluded.content; + } + if (text) { + const splitTexts = await textSplitter(text); + const numSplits = splitTexts.length; + if (partialStrategy === "last") { + splitTexts.reverse(); + } + for (let _ = 0; _ < numSplits - 1; _ += 1) { + splitTexts.pop(); + excluded.content = splitTexts.join(""); + if ((await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <= + maxTokens) { + if (partialStrategy === "last") { + excluded.content = [...splitTexts].reverse().join(""); + } + messagesCopy = [...messagesCopy.slice(0, idx), excluded]; + idx += 1; + break; } } } } - if (this.func && finalOutput !== undefined) { - await this.func(finalOutput, config); + } + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) { + idx -= 1; } } - /** - * A runnable that assigns key-value pairs to the input. - * - * The example below shows how you could use it with an inline function. - * - * @example - * ```typescript - * const prompt = - * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} - * Question: {question} - * SQL Query:`); - * - * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` - * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. - * // In this case, we're passing the schema. - * const sqlQueryGeneratorChain = RunnableSequence.from([ - * RunnablePassthrough.assign({ - * schema: async () => db.getTableInfo(), - * }), - * prompt, - * new ChatOpenAI({}).bind({ stop: ["\nSQLResult:"] }), - * new StringOutputParser(), - * ]); - * const result = await sqlQueryGeneratorChain.invoke({ - * question: "How many employees are there?", - * }); - * ``` - */ - static assign(mapping) { - return new RunnableAssign(new RunnableMap({ steps: mapping })); + return messagesCopy.slice(0, idx); +} +async function _lastMaxTokens(messages, options) { + const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options; + // Create a copy of messages to avoid mutation + let messagesCopy = messages.map((message) => { + const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); + }); + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (messagesCopy.length > 0 && + !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) { + messagesCopy = messagesCopy.slice(0, -1); + } + } + const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; + let reversed_ = swappedSystem + ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) + : messagesCopy.reverse(); + reversed_ = await _firstMaxTokens(reversed_, { + ...rest, + partialStrategy: allowPartial ? "last" : undefined, + endOn: startOn, + }); + if (swappedSystem) { + return [reversed_[0], ...reversed_.slice(1).reverse()]; + } + else { + return reversed_.reverse(); } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/is_zod_schema.js - -/** - * Given either a Zod schema, or plain object, determine if the input is a Zod schema. - * - * @param {z.ZodType | Record} input - * @returns {boolean} Whether or not the provided input is a Zod schema. - */ -function isZodSchema(input) { - if (!input) { - return false; +const _MSG_CHUNK_MAP = { + human: { + message: human_HumanMessage, + messageChunk: human_HumanMessageChunk, + }, + ai: { + message: ai_AIMessage, + messageChunk: ai_AIMessageChunk, + }, + system: { + message: system_SystemMessage, + messageChunk: system_SystemMessageChunk, + }, + developer: { + message: system_SystemMessage, + messageChunk: system_SystemMessageChunk, + }, + tool: { + message: tool_ToolMessage, + messageChunk: tool_ToolMessageChunk, + }, + function: { + message: function_FunctionMessage, + messageChunk: function_FunctionMessageChunk, + }, + generic: { + message: chat_ChatMessage, + messageChunk: chat_ChatMessageChunk, + }, + remove: { + message: RemoveMessage, + messageChunk: RemoveMessage, // RemoveMessage does not have a chunk class. + }, +}; +function _switchTypeToMessage(messageType, fields, returnChunk) { + let chunk; + let msg; + switch (messageType) { + case "human": + if (returnChunk) { + chunk = new HumanMessageChunk(fields); + } + else { + msg = new HumanMessage(fields); + } + break; + case "ai": + if (returnChunk) { + let aiChunkFields = { + ...fields, + }; + if ("tool_calls" in aiChunkFields) { + aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: undefined, + args: JSON.stringify(tc.args), + })), + }; + } + chunk = new AIMessageChunk(aiChunkFields); + } + else { + msg = new AIMessage(fields); + } + break; + case "system": + if (returnChunk) { + chunk = new SystemMessageChunk(fields); + } + else { + msg = new SystemMessage(fields); + } + break; + case "developer": + if (returnChunk) { + chunk = new SystemMessageChunk({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer", + }, + }); + } + else { + msg = new SystemMessage({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer", + }, + }); + } + break; + case "tool": + if ("tool_call_id" in fields) { + if (returnChunk) { + chunk = new ToolMessageChunk(fields); + } + else { + msg = new ToolMessage(fields); + } + } + else { + throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); + } + break; + case "function": + if (returnChunk) { + chunk = new FunctionMessageChunk(fields); + } + else { + if (!fields.name) { + throw new Error("FunctionMessage must have a 'name' field"); + } + msg = new FunctionMessage(fields); + } + break; + case "generic": + if ("role" in fields) { + if (returnChunk) { + chunk = new ChatMessageChunk(fields); + } + else { + msg = new ChatMessage(fields); + } + } + else { + throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); + } + break; + default: + throw new Error(`Unrecognized message type ${messageType}`); } - if (typeof input !== "object") { - return false; + if (returnChunk && chunk) { + return chunk; } - if (Array.isArray(input)) { - return false; + if (msg) { + return msg; } - const asZodSchema = input; - // relies on an internal property of Zod schemas, so this may break in the future, hence the - // additional fallback checks below - if (asZodSchema._def) { - return true; + throw new Error(`Unrecognized message type ${messageType}`); +} +function _chunkToMsg(chunk) { + const chunkType = chunk.getType(); + let msg; + const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); + if (chunkType in _MSG_CHUNK_MAP) { + msg = _switchTypeToMessage(chunkType, fields); } - const zodFirstPartyTypeKinds = Object.values(z.ZodFirstPartyTypeKind); - if (zodFirstPartyTypeKinds.includes(asZodSchema.constructor?.name ?? "NOT_INCLUDED")) { - return true; + if (!msg) { + throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); } - // if all else fails, assume based on the presence of parse, parseAsync, safeParse, and - // safeParseAsync, as these are characteristic of Zod schemas - return (typeof asZodSchema.parse === "function" && - typeof asZodSchema.parseAsync === "function" && - typeof asZodSchema.safeParse === "function" && - typeof asZodSchema.safeParseAsync === "function"); + return msg; +} +/** + * The default text splitter function that splits text by newlines. + * + * @param {string} text + * @returns A promise that resolves to an array of strings split by newlines. + */ +function defaultTextSplitter(text) { + const splits = text.split("\n"); + return Promise.resolve([ + ...splits.slice(0, -1).map((s) => `${s}\n`), + splits[splits.length - 1], + ]); } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js @@ -102477,668 +112605,561 @@ function isZodSchema(input) { -/** - * Creates a transform stream for encoding chat message chunks. - * @deprecated Use {@link BytesOutputParser} instead - * @returns A TransformStream instance that encodes chat message chunks. - */ -function createChatMessageChunkEncoderStream() { - const textEncoder = new TextEncoder(); - return new TransformStream({ - transform(chunk, controller) { - controller.enqueue(textEncoder.encode(typeof chunk.content === "string" - ? chunk.content - : JSON.stringify(chunk.content))); - }, - }); -} -function _formatForTracing(messages) { - const messagesToTrace = []; - for (const message of messages) { - let messageToTrace = message; - if (Array.isArray(message.content)) { - for (let idx = 0; idx < message.content.length; idx++) { - const block = message.content[idx]; - if (isURLContentBlock(block) || isBase64ContentBlock(block)) { - if (messageToTrace === message) { - // Also shallow-copy content - // eslint-disable-next-line @typescript-eslint/no-explicit-any - messageToTrace = new message.constructor({ - ...messageToTrace, - content: [ - ...message.content.slice(0, idx), - convertToOpenAIImageBlock(block), - ...message.content.slice(idx + 1), - ], - }); - } - } - } - } - messagesToTrace.push(messageToTrace); - } - return messagesToTrace; -} -/** - * Base class for chat models. It extends the BaseLanguageModel class and - * provides methods for generating chat based on input messages. +// TODO: Use a star export when we deprecate the +// existing "ToolCall" type in "base.js". + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/messages.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha1/hash.js +// @ts-nocheck +// Inlined to deal with portability issues with importing crypto module +/* + * [js-sha1]{@link https://github.com/emn178/js-sha1} + * + * @version 0.6.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT */ -class BaseChatModel extends BaseLanguageModel { - constructor(fields) { - super(fields); - // Only ever instantiated in main LangChain - Object.defineProperty(this, "lc_namespace", { - enumerable: true, - configurable: true, - writable: true, - value: ["langchain", "chat_models", this._llmType()] - }); - Object.defineProperty(this, "disableStreaming", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); +/*jslint bitwise: true */ + +var root = typeof window === "object" ? window : {}; +var HEX_CHARS = "0123456789abcdef".split(""); +var EXTRA = [-2147483648, 8388608, 32768, 128]; +var SHIFT = [24, 16, 8, 0]; +var OUTPUT_TYPES = (/* unused pure expression or super */ null && (["hex", "array", "digest", "arrayBuffer"])); +var blocks = []; +function Sha1(sharedMemory) { + if (sharedMemory) { + blocks[0] = + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + this.blocks = blocks; } - _separateRunnableConfigFromCallOptionsCompat(options) { - // For backwards compat, keep `signal` in both runnableConfig and callOptions - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; + else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } - /** - * Invokes the chat model with a single input. - * @param input The input for the language model. - * @param options The call options. - * @returns A Promise that resolves to a BaseMessageChunk. - */ - async invoke(input, options) { - const promptValue = BaseChatModel._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - const chatGeneration = result.generations[0][0]; - // TODO: Remove cast after figuring out inheritance - return chatGeneration.message; + this.h0 = 0x67452301; + this.h1 = 0xefcdab89; + this.h2 = 0x98badcfe; + this.h3 = 0x10325476; + this.h4 = 0xc3d2e1f0; + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; +} +Sha1.prototype.update = function (message) { + if (this.finalized) { + return; } - // eslint-disable-next-line require-yield - async *_streamResponseChunks(_messages, _options, _runManager) { - throw new Error("Not implemented."); + var notString = typeof message !== "string"; + if (notString && message.constructor === root.ArrayBuffer) { + message = new Uint8Array(message); } - async *_streamIterator(input, options) { - // Subclass check required to avoid double callbacks with default implementation - if (this._streamResponseChunks === - BaseChatModel.prototype._streamResponseChunks || - this.disableStreaming) { - yield this.invoke(input, options); + var code, index = 0, i, length = message.length || 0, blocks = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + if (notString) { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } } else { - const prompt = BaseChatModel._convertInputToPromptValue(input); - const messages = prompt.toChatMessages(); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const inheritableMetadata = { - ...runnableConfig.metadata, - ...this.getLsParams(callOptions), - }; - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), - batch_size: 1, - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); - let generationChunk; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let llmOutput; - try { - for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - chunk.message._updateId(`run-${runId}`); - } - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata, - }; - yield chunk.message; - if (!generationChunk) { - generationChunk = chunk; - } - else { - generationChunk = generationChunk.concat(chunk); - } - if (isAIMessageChunk(chunk.message) && - chunk.message.usage_metadata !== undefined) { - llmOutput = { - tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens, - }, - }; - } + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } + else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + else { + code = + 0x10000 + + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } - catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - // TODO: Remove cast after figuring out inheritance - generations: [[generationChunk]], - llmOutput, - }))); + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } + else { + this.start = i; } } - getLsParams(options) { - const providerName = this.getName().startsWith("Chat") - ? this.getName().replace("Chat", "") - : this.getName(); + if (this.bytes > 4294967295) { + this.hBytes += (this.bytes / 4294967296) << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha1.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >> 2] |= EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = this.block; + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); + blocks[15] = this.bytes << 3; + this.hash(); +}; +Sha1.prototype.hash = function () { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4; + var f, j, t, blocks = this.blocks; + for (j = 16; j < 80; ++j) { + t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; + blocks[j] = (t << 1) | (t >>> 31); + } + for (j = 0; j < 20; j += 5) { + f = (b & c) | (~b & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1518500249 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = (a & b) | (~a & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1518500249 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = (e & a) | (~e & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1518500249 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = (d & e) | (~d & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1518500249 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = (c & d) | (~c & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1518500249 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + for (; j < 40; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e + 1859775393 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d + 1859775393 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c + 1859775393 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b + 1859775393 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a + 1859775393 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + for (; j < 60; j += 5) { + f = (b & c) | (b & d) | (c & d); + t = (a << 5) | (a >>> 27); + e = (t + f + e - 1894007588 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = (a & b) | (a & c) | (b & c); + t = (e << 5) | (e >>> 27); + d = (t + f + d - 1894007588 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = (e & a) | (e & b) | (a & b); + t = (d << 5) | (d >>> 27); + c = (t + f + c - 1894007588 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = (d & e) | (d & a) | (e & a); + t = (c << 5) | (c >>> 27); + b = (t + f + b - 1894007588 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = (c & d) | (c & e) | (d & e); + t = (b << 5) | (b >>> 27); + a = (t + f + a - 1894007588 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + for (; j < 80; j += 5) { + f = b ^ c ^ d; + t = (a << 5) | (a >>> 27); + e = (t + f + e - 899497514 + blocks[j]) << 0; + b = (b << 30) | (b >>> 2); + f = a ^ b ^ c; + t = (e << 5) | (e >>> 27); + d = (t + f + d - 899497514 + blocks[j + 1]) << 0; + a = (a << 30) | (a >>> 2); + f = e ^ a ^ b; + t = (d << 5) | (d >>> 27); + c = (t + f + c - 899497514 + blocks[j + 2]) << 0; + e = (e << 30) | (e >>> 2); + f = d ^ e ^ a; + t = (c << 5) | (c >>> 27); + b = (t + f + b - 899497514 + blocks[j + 3]) << 0; + d = (d << 30) | (d >>> 2); + f = c ^ d ^ e; + t = (b << 5) | (b >>> 27); + a = (t + f + a - 899497514 + blocks[j + 4]) << 0; + c = (c << 30) | (c >>> 2); + } + this.h0 = (this.h0 + a) << 0; + this.h1 = (this.h1 + b) << 0; + this.h2 = (this.h2 + c) << 0; + this.h3 = (this.h3 + d) << 0; + this.h4 = (this.h4 + e) << 0; +}; +Sha1.prototype.hex = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; + return (HEX_CHARS[(h0 >> 28) & 0x0f] + + HEX_CHARS[(h0 >> 24) & 0x0f] + + HEX_CHARS[(h0 >> 20) & 0x0f] + + HEX_CHARS[(h0 >> 16) & 0x0f] + + HEX_CHARS[(h0 >> 12) & 0x0f] + + HEX_CHARS[(h0 >> 8) & 0x0f] + + HEX_CHARS[(h0 >> 4) & 0x0f] + + HEX_CHARS[h0 & 0x0f] + + HEX_CHARS[(h1 >> 28) & 0x0f] + + HEX_CHARS[(h1 >> 24) & 0x0f] + + HEX_CHARS[(h1 >> 20) & 0x0f] + + HEX_CHARS[(h1 >> 16) & 0x0f] + + HEX_CHARS[(h1 >> 12) & 0x0f] + + HEX_CHARS[(h1 >> 8) & 0x0f] + + HEX_CHARS[(h1 >> 4) & 0x0f] + + HEX_CHARS[h1 & 0x0f] + + HEX_CHARS[(h2 >> 28) & 0x0f] + + HEX_CHARS[(h2 >> 24) & 0x0f] + + HEX_CHARS[(h2 >> 20) & 0x0f] + + HEX_CHARS[(h2 >> 16) & 0x0f] + + HEX_CHARS[(h2 >> 12) & 0x0f] + + HEX_CHARS[(h2 >> 8) & 0x0f] + + HEX_CHARS[(h2 >> 4) & 0x0f] + + HEX_CHARS[h2 & 0x0f] + + HEX_CHARS[(h3 >> 28) & 0x0f] + + HEX_CHARS[(h3 >> 24) & 0x0f] + + HEX_CHARS[(h3 >> 20) & 0x0f] + + HEX_CHARS[(h3 >> 16) & 0x0f] + + HEX_CHARS[(h3 >> 12) & 0x0f] + + HEX_CHARS[(h3 >> 8) & 0x0f] + + HEX_CHARS[(h3 >> 4) & 0x0f] + + HEX_CHARS[h3 & 0x0f] + + HEX_CHARS[(h4 >> 28) & 0x0f] + + HEX_CHARS[(h4 >> 24) & 0x0f] + + HEX_CHARS[(h4 >> 20) & 0x0f] + + HEX_CHARS[(h4 >> 16) & 0x0f] + + HEX_CHARS[(h4 >> 12) & 0x0f] + + HEX_CHARS[(h4 >> 8) & 0x0f] + + HEX_CHARS[(h4 >> 4) & 0x0f] + + HEX_CHARS[h4 & 0x0f]); +}; +Sha1.prototype.toString = Sha1.prototype.hex; +Sha1.prototype.digest = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4; + return [ + (h0 >> 24) & 0xff, + (h0 >> 16) & 0xff, + (h0 >> 8) & 0xff, + h0 & 0xff, + (h1 >> 24) & 0xff, + (h1 >> 16) & 0xff, + (h1 >> 8) & 0xff, + h1 & 0xff, + (h2 >> 24) & 0xff, + (h2 >> 16) & 0xff, + (h2 >> 8) & 0xff, + h2 & 0xff, + (h3 >> 24) & 0xff, + (h3 >> 16) & 0xff, + (h3 >> 8) & 0xff, + h3 & 0xff, + (h4 >> 24) & 0xff, + (h4 >> 16) & 0xff, + (h4 >> 8) & 0xff, + h4 & 0xff, + ]; +}; +Sha1.prototype.array = Sha1.prototype.digest; +Sha1.prototype.arrayBuffer = function () { + this.finalize(); + var buffer = new ArrayBuffer(20); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + return buffer; +}; +const insecureHash = (message) => { + return new Sha1(true).update(message)["hex"](); +}; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/base.js + + +/** + * This cache key should be consistent across all versions of LangChain. + * It is currently NOT consistent across versions of LangChain. + * + * A huge benefit of having a remote cache (like redis) is that you can + * access the cache from different processes/machines. The allows you to + * separate concerns and scale horizontally. + * + * TODO: Make cache key consistent across versions of LangChain. + */ +const getCacheKey = (...strings) => insecureHash(strings.join("_")); +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== undefined) { return { - ls_model_type: "chat", - ls_stop: options.stop, - ls_provider: providerName, + text: storedGeneration.text, + message: mapStoredMessageToChatMessage(storedGeneration.message), }; } - /** @ignore */ - async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - let runManagers; - if (startedRunManagers !== undefined && - startedRunManagers.length === baseMessages.length) { - runManagers = startedRunManagers; - } - else { - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions), - }; - // create callback manager and start run - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1, - }; - runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); - } - const generations = []; - const llmOutputs = []; - // Even if stream is not explicitly called, check if model is implicitly - // called from streamEvents() or streamLog() to get all streamed events. - // Bail out if _streamResponseChunks not overridden - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - if (hasStreamingHandler && - !this.disableStreaming && - baseMessages.length === 1 && - this._streamResponseChunks !== - BaseChatModel.prototype._streamResponseChunks) { - try { - const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); - let aggregated; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let llmOutput; - for await (const chunk of stream) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - chunk.message._updateId(`run-${runId}`); - } - if (aggregated === undefined) { - aggregated = chunk; - } - else { - aggregated = concat(aggregated, chunk); - } - if (isAIMessageChunk(chunk.message) && - chunk.message.usage_metadata !== undefined) { - llmOutput = { - tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens, - }, - }; - } - } - if (aggregated === undefined) { - throw new Error("Received empty response from chat model call."); - } - generations.push([aggregated]); - await runManagers?.[0].handleLLMEnd({ - generations, - llmOutput, - }); - } - catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - } - else { - // generate results - const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); - // handle results - await Promise.all(results.map(async (pResult, i) => { - if (pResult.status === "fulfilled") { - const result = pResult.value; - for (const generation of result.generations) { - if (generation.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) - generation.message._updateId(`run-${runId}`); - } - generation.message.response_metadata = { - ...generation.generationInfo, - ...generation.message.response_metadata, - }; - } - if (result.generations.length === 1) { - result.generations[0].message.response_metadata = { - ...result.llmOutput, - ...result.generations[0].message.response_metadata, - }; - } - generations[i] = result.generations; - llmOutputs[i] = result.llmOutput; - return runManagers?.[i]?.handleLLMEnd({ - generations: [result.generations], - llmOutput: result.llmOutput, - }); - } - else { - // status === "rejected" - await runManagers?.[i]?.handleLLMError(pResult.reason); - return Promise.reject(pResult.reason); - } - })); - } - // create combined output - const output = { - generations, - llmOutput: llmOutputs.length - ? this._combineLLMOutput?.(...llmOutputs) - : undefined, - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers - ? { runIds: runManagers?.map((manager) => manager.runId) } - : undefined, - configurable: true, - }); - return output; + else { + return { text: storedGeneration.text }; } - async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }) { - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions), - }; - // create callback manager and start run - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1, - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); - // generate results - const missingPromptIndices = []; - const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { - // Join all content into one string for the prompt index - const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); - const result = await cache.lookup(prompt, llmStringKey); - if (result == null) { - missingPromptIndices.push(index); - } - return result; - })); - // Map run managers to the results before filtering out null results - // Null results are just absent from the cache. - const cachedResults = results - .map((result, index) => ({ result, runManager: runManagers?.[index] })) - .filter(({ result }) => (result.status === "fulfilled" && result.value != null) || - result.status === "rejected"); - // Handle results and call run managers - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result) => { - if ("message" in result && - isBaseMessage(result.message) && - isAIMessage(result.message)) { - // eslint-disable-next-line no-param-reassign - result.message.usage_metadata = { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0, - }; - } - // eslint-disable-next-line no-param-reassign - result.generationInfo = { - ...result.generationInfo, - tokenUsage: {}, - }; - return result; - }); - if (result.length) { - await runManager?.handleLLMNewToken(result[0].text); - } - return runManager?.handleLLMEnd({ - generations: [result], - }, undefined, undefined, undefined, { - cached: true, - }); - } - else { - // status === "rejected" - await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { - cached: true, - }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers, - }; - // This defines RUN_KEY as a non-enumerable property on the output object - // so that it is not serialized when the output is stringified, and so that - // it isnt included when listing the keys of the output object. - Object.defineProperty(output, RUN_KEY, { - value: runManagers - ? { runIds: runManagers?.map((manager) => manager.runId) } - : undefined, +} +function serializeGeneration(generation) { + const serializedValue = { + text: generation.text, + }; + if (generation.message !== undefined) { + serializedValue.message = generation.message.toDict(); + } + return serializedValue; +} +/** + * Base class for all caches. All caches should extend this class. + */ +class BaseCache { +} +const GLOBAL_MAP = new Map(); +/** + * A cache for storing LLM generations that stores data in memory. + */ +class InMemoryCache extends BaseCache { + constructor(map) { + super(); + Object.defineProperty(this, "cache", { + enumerable: true, configurable: true, + writable: true, + value: void 0 }); - return output; + this.cache = map ?? new Map(); } /** - * Generates chat based on the input messages. - * @param messages An array of arrays of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. */ - async generate(messages, options, callbacks) { - // parse call options - let parsedOptions; - if (Array.isArray(options)) { - parsedOptions = { stop: options }; - } - else { - parsedOptions = options; - } - const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) { - return this._generateUncached(baseMessages, callOptions, runnableConfig); - } - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - messages: baseMessages, - cache, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig, - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== undefined - ? missingPromptIndices.map((i) => startedRunManagers?.[i]) - : undefined); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - // Join all content into one string for the prompt index - const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); - return cache.update(prompt, llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { generations, llmOutput }; + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); } /** - * Get the parameters used to invoke the model + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - invocationParams(_options) { - return {}; - } - _modelType() { - return "base_chat_model"; + async update(prompt, llmKey, value) { + this.cache.set(getCacheKey(prompt, llmKey), value); } /** - * @deprecated - * Return a json-like object representing this LLM. + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. */ - serialize() { - return { - ...this.invocationParams(), - _type: this._llmType(), - _model: this._modelType(), - }; + static global() { + return new InMemoryCache(GLOBAL_MAP); } - /** - * Generates a prompt based on the input prompt values. - * @param promptValues An array of BasePromptValue instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generatePrompt(promptValues, options, callbacks) { - const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); - return this.generate(promptMessages, options, callbacks); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js + + + +/** + * Base PromptValue class. All prompt values should extend this class. + */ +class BasePromptValue extends Serializable { +} +/** + * Represents a prompt value as a string. It extends the BasePromptValue + * class and overrides the toString and toChatMessages methods. + */ +class StringPromptValue extends BasePromptValue { + static lc_name() { + return "StringPromptValue"; } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Makes a single call to the chat model. - * @param messages An array of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. - */ - async call(messages, options, callbacks) { - const result = await this.generate([messages.map(coerceMessageLikeToMessage)], options, callbacks); - const generations = result.generations; - return generations[0][0].message; + constructor(value) { + super({ value }); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompt_values"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.value = value; } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Makes a single call to the chat model with a prompt value. - * @param promptValue The value of the prompt. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. - */ - async callPrompt(promptValue, options, callbacks) { - const promptMessages = promptValue.toChatMessages(); - return this.call(promptMessages, options, callbacks); + toString() { + return this.value; } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Predicts the next message based on the input messages. - * @param messages An array of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a BaseMessage. - */ - async predictMessages(messages, options, callbacks) { - return this.call(messages, options, callbacks); + toChatMessages() { + return [new human_HumanMessage(this.value)]; } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.2.0. - * - * Predicts the next message based on a text input. - * @param text The text input. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to a string. - */ - async predict(text, options, callbacks) { - const message = new human_HumanMessage(text); - const result = await this.call([message], options, callbacks); - if (typeof result.content !== "string") { - throw new Error("Cannot use predict when output is not a string."); - } - return result.content; +} +/** + * Class that represents a chat prompt value. It extends the + * BasePromptValue and includes an array of BaseMessage instances. + */ +class ChatPromptValue extends BasePromptValue { + static lc_name() { + return "ChatPromptValue"; } - withStructuredOutput(outputSchema, config) { - if (typeof this.bindTools !== "function") { - throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); - } - if (config?.strict) { - throw new Error(`"strict" mode is not supported for this model by default.`); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const schema = outputSchema; - const name = config?.name; - const description = schema.description ?? "A function available to call."; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") { - throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); - } - let functionName = name ?? "extract"; - let tools; - if (isZodSchema(schema)) { - tools = [ - { - type: "function", - function: { - name: functionName, - description, - parameters: zodToJsonSchema_zodToJsonSchema(schema), - }, - }, - ]; - } - else { - if ("name" in schema) { - functionName = schema.name; - } - tools = [ - { - type: "function", - function: { - name: functionName, - description, - parameters: schema, - }, - }, - ]; - } - const llm = this.bindTools(tools); - const outputParser = base_RunnableLambda.from((input) => { - if (!input.tool_calls || input.tool_calls.length === 0) { - throw new Error("No tool calls found in the response."); - } - const toolCall = input.tool_calls.find((tc) => tc.name === functionName); - if (!toolCall) { - throw new Error(`No tool call found with name ${functionName}.`); - } - return toolCall.args; - }); - if (!includeRaw) { - return llm.pipe(outputParser).withConfig({ - runName: "StructuredOutput", - }); + constructor(fields) { + if (Array.isArray(fields)) { + // eslint-disable-next-line no-param-reassign + fields = { messages: fields }; } - const parserAssign = RunnablePassthrough.assign({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - parsed: (input, config) => outputParser.invoke(input.raw, config), - }); - const parserNone = RunnablePassthrough.assign({ - parsed: () => null, + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "prompt_values"] }); - const parsedWithFallback = parserAssign.withFallbacks({ - fallbacks: [parserNone], + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true }); - return RunnableSequence.from([ - { - raw: llm, - }, - parsedWithFallback, - ]).withConfig({ - runName: "StructuredOutputRunnable", + Object.defineProperty(this, "messages", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); + this.messages = fields.messages; } -} -/** - * An abstract class that extends BaseChatModel and provides a simple - * implementation of _generate. - */ -class SimpleChatModel extends (/* unused pure expression or super */ null && (BaseChatModel)) { - async _generate(messages, options, runManager) { - const text = await this._call(messages, options, runManager); - const message = new AIMessage(text); - if (typeof message.content !== "string") { - throw new Error("Cannot generate with a simple chat model when output is not a string."); - } - return { - generations: [ - { - text: message.content, - message, - }, - ], - }; + toString() { + return getBufferString(this.messages); + } + toChatMessages() { + return this.messages; } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/language_models/chat_models.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/outputs.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/async_caller.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js - - /** - * A runnable that routes to a set of runnables based on Input['key']. - * Returns the output of the selected runnable. - * @example - * ```typescript - * import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; - * - * const router = new RouterRunnable({ - * runnables: { - * toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), - * reverseText: RunnableLambda.from((text: string) => - * text.split("").reverse().join("") - * ), - * }, - * }); - * - * // Invoke the 'reverseText' runnable - * const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); - * - * // "dlroW olleH" - * - * // Invoke the 'toUpperCase' runnable - * const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); - * - * // "HELLO WORLD" - * ``` + * Class that represents an image prompt value. It extends the + * BasePromptValue and includes an ImageURL instance. */ -class RouterRunnable extends Runnable { +class ImagePromptValue extends BasePromptValue { static lc_name() { - return "RouterRunnable"; + return "ImagePromptValue"; } constructor(fields) { + if (!("imageUrl" in fields)) { + // eslint-disable-next-line no-param-reassign + fields = { imageUrl: fields }; + } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "runnables"] + value: ["langchain_core", "prompt_values"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, @@ -103146,519 +113167,718 @@ class RouterRunnable extends Runnable { writable: true, value: true }); - Object.defineProperty(this, "runnables", { + Object.defineProperty(this, "imageUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.runnables = fields.runnables; + /** @ignore */ + Object.defineProperty(this, "value", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.imageUrl = fields.imageUrl; } - async invoke(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) { - throw new Error(`No runnable associated with key "${key}".`); - } - return runnable.invoke(actualInput, ensureConfig(options)); + toString() { + return this.imageUrl.url; } - async batch(inputs, options, batchOptions) { - const keys = inputs.map((input) => input.key); - const actualInputs = inputs.map((input) => input.input); - const missingKey = keys.find((key) => this.runnables[key] === undefined); - if (missingKey !== undefined) { - throw new Error(`One or more keys do not have a corresponding runnable.`); - } - const runnables = keys.map((key) => this.runnables[key]); - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; - const batchResults = []; - for (let i = 0; i < actualInputs.length; i += batchSize) { - const batchPromises = actualInputs - .slice(i, i + batchSize) - .map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); - const batchResult = await Promise.all(batchPromises); - batchResults.push(batchResult); - } - return batchResults.flat(); + toChatMessages() { + return [ + new human_HumanMessage({ + content: [ + { + type: "image_url", + image_url: { + detail: this.imageUrl.detail, + url: this.imageUrl.url, + }, + }, + ], + }), + ]; } - async stream(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === undefined) { - throw new Error(`No runnable associated with key "${key}".`); +} + +// EXTERNAL MODULE: ./node_modules/base64-js/index.js +var base64_js = __nccwpck_require__(8793); +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-YVJR5WRT.js + + +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/utils.ts +function never(_) { +} +function bytePairMerge(piece, ranks) { + let parts = Array.from( + { length: piece.length }, + (_, i) => ({ start: i, end: i + 1 }) + ); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; + } + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } + } + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function chunk_YVJR5WRT_escapeRegex(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = base64_js.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); + } + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); + } + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex( + Object.keys(this.specialTokens) + ); + const ret = []; + const allowedSpecialSet = new Set( + allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial + ); + const disallowedSpecialSet = new Set( + disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( + (x) => !allowedSpecialSet.has(x) + ) : disallowedSpecial + ); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error( + `The text contains a special token that is not allowed: ${specialMatch[0]}` + ); + } + } + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) + break; + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); + continue; } - return runnable.stream(actualInput, options); + ret.push(...bytePairEncode(piece, this.rankMap)); + } + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; + } + return ret; + } + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); + } +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => chunk_YVJR5WRT_escapeRegex(i)).join("|"), "g"); +}); +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; + } + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "davinci-002": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; + } + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; + } + case "ada": + case "babbage": + case "babbage-002": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; + } + case "gpt-3.5-turbo-instruct-0914": + case "gpt-3.5-turbo-instruct": + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "gpt-3.5-turbo-1106": + case "gpt-35-turbo": + case "gpt-4-1106-preview": + case "gpt-4-vision-preview": + case "gpt-3.5-turbo-0125": + case "gpt-4-turbo": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-turbo-preview": + case "gpt-4-0125-preview": + case "text-embedding-ada-002": + case "text-embedding-3-small": + case "text-embedding-3-large": { + return "cl100k_base"; + } + case "gpt-4o": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + case "gpt-4o-mini-2024-07-18": + case "gpt-4o-mini": + case "o1-mini": + case "o1-preview": + case "o1-preview-2024-09-12": + case "o1-mini-2024-09-12": + case "chatgpt-4o-latest": + case "gpt-4o-realtime": + case "gpt-4o-realtime-preview-2024-10-01": { + return "o200k_base"; + } + default: + throw new Error("Unknown model"); + } +} + + + +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js + + +const cache = {}; +const caller = /* #__PURE__ */ new async_caller_AsyncCaller({}); +async function getEncoding(encoding) { + if (!(encoding in cache)) { + cache[encoding] = caller + .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`) + .then((res) => res.json()) + .then((data) => new Tiktoken(data)) + .catch((e) => { + delete cache[encoding]; + throw e; + }); + } + return await cache[encoding]; +} +async function tiktoken_encodingForModel(model) { + return getEncoding(getEncodingNameForModel(model)); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js + + + + + + +// https://www.npmjs.com/package/js-tiktoken +const getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-3.5-turbo-16k")) { + return "gpt-3.5-turbo-16k"; + } + if (modelName.startsWith("gpt-3.5-turbo-")) { + return "gpt-3.5-turbo"; + } + if (modelName.startsWith("gpt-4-32k")) { + return "gpt-4-32k"; + } + if (modelName.startsWith("gpt-4-")) { + return "gpt-4"; + } + if (modelName.startsWith("gpt-4o")) { + return "gpt-4o"; + } + return modelName; +}; +const getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": + return 8191; + default: + return 2046; + } +}; +const getModelContextSize = (modelName) => { + switch (getModelNameForTiktoken(modelName)) { + case "gpt-3.5-turbo-16k": + return 16384; + case "gpt-3.5-turbo": + return 4096; + case "gpt-4-32k": + return 32768; + case "gpt-4": + return 8192; + case "text-davinci-003": + return 4097; + case "text-curie-001": + return 2048; + case "text-babbage-001": + return 2048; + case "text-ada-001": + return 2048; + case "code-davinci-002": + return 8000; + case "code-cushman-001": + return 2048; + default: + return 4097; + } +}; +/** + * Whether or not the input matches the OpenAI tool definition. + * @param {unknown} tool The input to check. + * @returns {boolean} Whether the input is an OpenAI tool definition. + */ +function isOpenAITool(tool) { + if (typeof tool !== "object" || !tool) + return false; + if ("type" in tool && + tool.type === "function" && + "function" in tool && + typeof tool.function === "object" && + tool.function && + "name" in tool.function && + "parameters" in tool.function) { + return true; + } + return false; +} +const calculateMaxTokens = async ({ prompt, modelName, }) => { + let numTokens; + try { + numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js - - - + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + // fallback to approximate calculation if tiktoken is not available + // each token is ~4 characters: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them# + numTokens = Math.ceil(prompt.length / 4); + } + const maxTokens = getModelContextSize(modelName); + return maxTokens - numTokens; +}; +const getVerbosity = () => false; /** - * Class that represents a runnable branch. The RunnableBranch is - * initialized with an array of branches and a default branch. When invoked, - * it evaluates the condition of each branch in order and executes the - * corresponding branch if the condition is true. If none of the conditions - * are true, it executes the default branch. - * @example - * ```typescript - * const branch = RunnableBranch.from([ - * [ - * (x: { topic: string; question: string }) => - * x.topic.toLowerCase().includes("anthropic"), - * anthropicChain, - * ], - * [ - * (x: { topic: string; question: string }) => - * x.topic.toLowerCase().includes("langchain"), - * langChainChain, - * ], - * generalChain, - * ]); - * - * const fullChain = RunnableSequence.from([ - * { - * topic: classificationChain, - * question: (input: { question: string }) => input.question, - * }, - * branch, - * ]); - * - * const result = await fullChain.invoke({ - * question: "how do I use LangChain?", - * }); - * ``` + * Base class for language models, chains, tools. */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -class RunnableBranch extends Runnable { - static lc_name() { - return "RunnableBranch"; +class BaseLangChain extends Runnable { + get lc_attributes() { + return { + callbacks: undefined, + verbose: undefined, + }; } - constructor(fields) { - super(fields); - Object.defineProperty(this, "lc_namespace", { + constructor(params) { + super(params); + /** + * Whether to print out response text. + */ + Object.defineProperty(this, "verbose", { enumerable: true, configurable: true, writable: true, - value: ["langchain_core", "runnables"] + value: void 0 }); - Object.defineProperty(this, "lc_serializable", { + Object.defineProperty(this, "callbacks", { enumerable: true, configurable: true, writable: true, - value: true + value: void 0 }); - Object.defineProperty(this, "default", { + Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "branches", { + Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.branches = fields.branches; - this.default = fields.default; - } - /** - * Convenience method for instantiating a RunnableBranch from - * RunnableLikes (objects, functions, or Runnables). - * - * Each item in the input except for the last one should be a - * tuple with two items. The first is a "condition" RunnableLike that - * returns "true" if the second RunnableLike in the tuple should run. - * - * The final item in the input should be a RunnableLike that acts as a - * default branch if no other branches match. - * - * @example - * ```ts - * import { RunnableBranch } from "@langchain/core/runnables"; - * - * const branch = RunnableBranch.from([ - * [(x: number) => x > 0, (x: number) => x + 1], - * [(x: number) => x < 0, (x: number) => x - 1], - * (x: number) => x - * ]); - * ``` - * @param branches An array where the every item except the last is a tuple of [condition, runnable] - * pairs. The last item is a default runnable which is invoked if no other condition matches. - * @returns A new RunnableBranch. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static from(branches) { - if (branches.length < 1) { - throw new Error("RunnableBranch requires at least one branch"); - } - const branchLikes = branches.slice(0, -1); - const coercedBranches = branchLikes.map(([condition, runnable]) => [ - _coerceToRunnable(condition), - _coerceToRunnable(runnable), - ]); - const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); - return new this({ - branches: coercedBranches, - default: defaultBranch, - }); - } - async _invoke(input, config, runManager) { - let result; - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`condition:${i + 1}`), - })); - if (conditionValue) { - result = await branchRunnable.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`branch:${i + 1}`), - })); - break; - } - } - if (!result) { - result = await this.default.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild("branch:default"), - })); - } - return result; - } - async invoke(input, config = {}) { - return this._callWithConfig(this._invoke, input, config); - } - async *_streamIterator(input, config) { - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, undefined, undefined, undefined, config?.runName); - let finalOutput; - let finalOutputSupported = true; - let stream; - try { - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, patchConfig(config, { - callbacks: runManager?.getChild(`condition:${i + 1}`), - })); - if (conditionValue) { - stream = await branchRunnable.stream(input, patchConfig(config, { - callbacks: runManager?.getChild(`branch:${i + 1}`), - })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } - } - break; - } - } - if (stream === undefined) { - stream = await this.default.stream(input, patchConfig(config, { - callbacks: runManager?.getChild("branch:default"), - })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) { - if (finalOutput === undefined) { - finalOutput = chunk; - } - else { - try { - finalOutput = concat(finalOutput, chunk); - } - catch (e) { - finalOutput = undefined; - finalOutputSupported = false; - } - } - } - } - } - } - catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; } } - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js - - - /** - * Wraps a LCEL chain and manages history. It appends input messages - * and chain outputs as history, and adds the current history messages to - * the chain input. - * @example - * ```typescript - * // yarn add @langchain/anthropic @langchain/community @upstash/redis - * - * import { - * ChatPromptTemplate, - * MessagesPlaceholder, - * } from "@langchain/core/prompts"; - * import { ChatAnthropic } from "@langchain/anthropic"; - * import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; - * // For demos, you can also use an in-memory store: - * // import { ChatMessageHistory } from "langchain/stores/message/in_memory"; - * - * const prompt = ChatPromptTemplate.fromMessages([ - * ["system", "You're an assistant who's good at {ability}"], - * new MessagesPlaceholder("history"), - * ["human", "{question}"], - * ]); - * - * const chain = prompt.pipe(new ChatAnthropic({})); - * - * const chainWithHistory = new RunnableWithMessageHistory({ - * runnable: chain, - * getMessageHistory: (sessionId) => - * new UpstashRedisChatMessageHistory({ - * sessionId, - * config: { - * url: process.env.UPSTASH_REDIS_REST_URL!, - * token: process.env.UPSTASH_REDIS_REST_TOKEN!, - * }, - * }), - * inputMessagesKey: "question", - * historyMessagesKey: "history", - * }); - * - * const result = await chainWithHistory.invoke( - * { - * ability: "math", - * question: "What does cosine mean?", - * }, - * { - * configurable: { - * sessionId: "some_string_identifying_a_user", - * }, - * } - * ); - * - * const result2 = await chainWithHistory.invoke( - * { - * ability: "math", - * question: "What's its inverse?", - * }, - * { - * configurable: { - * sessionId: "some_string_identifying_a_user", - * }, - * } - * ); - * ``` + * Base class for language models. */ -class RunnableWithMessageHistory extends RunnableBinding { - constructor(fields) { - let historyChain = base_RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); - const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; - if (messagesKey) { - historyChain = RunnablePassthrough.assign({ - [messagesKey]: historyChain, - }).withConfig({ runName: "insertHistory" }); - } - const bound = historyChain - .pipe(fields.runnable.withListeners({ - onEnd: (run, config) => this._exitHistory(run, config ?? {}), - })) - .withConfig({ runName: "RunnableWithMessageHistory" }); - const config = fields.config ?? {}; +class BaseLanguageModel extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; + } + constructor({ callbacks, callbackManager, ...params }) { + const { cache, ...rest } = params; super({ - ...fields, - config, - bound, - }); - Object.defineProperty(this, "runnable", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputMessagesKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + callbacks: callbacks ?? callbackManager, + ...rest, }); - Object.defineProperty(this, "outputMessagesKey", { + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "historyMessagesKey", { + Object.defineProperty(this, "cache", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "getMessageHistory", { + Object.defineProperty(this, "_encoding", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.runnable = fields.runnable; - this.getMessageHistory = fields.getMessageHistory; - this.inputMessagesKey = fields.inputMessagesKey; - this.outputMessagesKey = fields.outputMessagesKey; - this.historyMessagesKey = fields.historyMessagesKey; - } - _getInputMessages( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - inputValue) { - let parsedInputValue; - if (typeof inputValue === "object" && - !Array.isArray(inputValue) && - !isBaseMessage(inputValue)) { - let key; - if (this.inputMessagesKey) { - key = this.inputMessagesKey; - } - else if (Object.keys(inputValue).length === 1) { - key = Object.keys(inputValue)[0]; - } - else { - key = "input"; - } - if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) { - parsedInputValue = inputValue[key][0]; - } - else { - parsedInputValue = inputValue[key]; - } - } - else { - parsedInputValue = inputValue; - } - if (typeof parsedInputValue === "string") { - return [new human_HumanMessage(parsedInputValue)]; - } - else if (Array.isArray(parsedInputValue)) { - return parsedInputValue; + if (typeof cache === "object") { + this.cache = cache; } - else if (isBaseMessage(parsedInputValue)) { - return [parsedInputValue]; + else if (cache) { + this.cache = InMemoryCache.global(); } else { - throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); + this.cache = undefined; } + this.caller = new async_caller_AsyncCaller(params ?? {}); } - _getOutputMessages( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - outputValue) { - let parsedOutputValue; - if (!Array.isArray(outputValue) && - !isBaseMessage(outputValue) && - typeof outputValue !== "string") { - let key; - if (this.outputMessagesKey !== undefined) { - key = this.outputMessagesKey; - } - else if (Object.keys(outputValue).length === 1) { - key = Object.keys(outputValue)[0]; + async getNumTokens(content) { + // TODO: Figure out correct value. + if (typeof content !== "string") { + return 0; + } + // fallback to approximate calculation if tiktoken is not available + let numTokens = Math.ceil(content.length / 4); + if (!this._encoding) { + try { + this._encoding = await tiktoken_encodingForModel("modelName" in this + ? getModelNameForTiktoken(this.modelName) + : "gpt2"); } - else { - key = "output"; + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } - // If you are wrapping a chat model directly - // The output is actually this weird generations object - if (outputValue.generations !== undefined) { - parsedOutputValue = outputValue.generations[0][0].message; + } + if (this._encoding) { + try { + numTokens = this._encoding.encode(content).length; } - else { - parsedOutputValue = outputValue[key]; + catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } } - else { - parsedOutputValue = outputValue; - } - if (typeof parsedOutputValue === "string") { - return [new ai_AIMessage(parsedOutputValue)]; - } - else if (Array.isArray(parsedOutputValue)) { - return parsedOutputValue; + return numTokens; + } + static _convertInputToPromptValue(input) { + if (typeof input === "string") { + return new StringPromptValue(input); } - else if (isBaseMessage(parsedOutputValue)) { - return [parsedOutputValue]; + else if (Array.isArray(input)) { + return new ChatPromptValue(input.map(coerceMessageLikeToMessage)); } else { - throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); + return input; } } - async _enterHistory( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - input, kwargs) { - const history = kwargs?.configurable?.messageHistory; - const messages = await history.getMessages(); - if (this.historyMessagesKey === undefined) { - return messages.concat(this._getInputMessages(input)); + /** + * Get the identifying parameters of the LLM. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + _identifyingParams() { + return {}; + } + /** + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. + */ + _getSerializedCacheKeyParametersForCall( + // TODO: Fix when we remove the RunnableLambda backwards compatibility shim. + { config, ...callOptions }) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType(), + }; + const filteredEntries = Object.entries(params).filter(([_, value]) => value !== undefined); + const serializedEntries = filteredEntries + .map(([key, value]) => `${key}:${JSON.stringify(value)}`) + .sort() + .join(","); + return serializedEntries; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType(), + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(_data) { + throw new Error("Use .toJSON() instead"); + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js + + + +/** + * A runnable to passthrough inputs unchanged or with additional keys. + * + * This runnable behaves almost like the identity function, except that it + * can be configured to add additional keys to the output, if the input is + * an object. + * + * The example below demonstrates how to use `RunnablePassthrough to + * passthrough the input from the `.invoke()` + * + * @example + * ```typescript + * const chain = RunnableSequence.from([ + * { + * question: new RunnablePassthrough(), + * context: async () => loadContextFromStore(), + * }, + * prompt, + * llm, + * outputParser, + * ]); + * const response = await chain.invoke( + * "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." + * ); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class RunnablePassthrough extends Runnable { + static lc_name() { + return "RunnablePassthrough"; + } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "func", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (fields) { + this.func = fields.func; } - return messages; } - async _exitHistory(run, config) { - const history = config.configurable?.messageHistory; - // Get input messages - let inputs; - // Chat model inputs are nested arrays - if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) { - inputs = run.inputs[0]; - } - else { - inputs = run.inputs; + async invoke(input, options) { + const config = ensureConfig(options); + if (this.func) { + await this.func(input, config); } - let inputMessages = this._getInputMessages(inputs); - // If historic messages were prepended to the input messages, remove them to - // avoid adding duplicate messages to history. - if (this.historyMessagesKey === undefined) { - const existingMessages = await history.getMessages(); - inputMessages = inputMessages.slice(existingMessages.length); + return this._callWithConfig((input) => Promise.resolve(input), input, config); + } + async *transform(generator, options) { + const config = ensureConfig(options); + let finalOutput; + let finalOutputSupported = true; + for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + finalOutput = concat(finalOutput, chunk); + } + catch { + finalOutput = undefined; + finalOutputSupported = false; + } + } + } } - // Get output messages - const outputValue = run.outputs; - if (!outputValue) { - throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); + if (this.func && finalOutput !== undefined) { + await this.func(finalOutput, config); } - const outputMessages = this._getOutputMessages(outputValue); - await history.addMessages([...inputMessages, ...outputMessages]); } - async _mergeConfig(...configs) { - const config = await super._mergeConfig(...configs); - // Extract sessionId - if (!config.configurable || !config.configurable.sessionId) { - const exampleInput = { - [this.inputMessagesKey ?? "input"]: "foo", - }; - const exampleConfig = { configurable: { sessionId: "123" } }; - throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\n` + - `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); - } - // attach messageHistory - const { sessionId } = config.configurable; - config.configurable.messageHistory = await this.getMessageHistory(sessionId); - return config; + /** + * A runnable that assigns key-value pairs to the input. + * + * The example below shows how you could use it with an inline function. + * + * @example + * ```typescript + * const prompt = + * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} + * Question: {question} + * SQL Query:`); + * + * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` + * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. + * // In this case, we're passing the schema. + * const sqlQueryGeneratorChain = RunnableSequence.from([ + * RunnablePassthrough.assign({ + * schema: async () => db.getTableInfo(), + * }), + * prompt, + * new ChatOpenAI({}).withConfig({ stop: ["\nSQLResult:"] }), + * new StringOutputParser(), + * ]); + * const result = await sqlQueryGeneratorChain.invoke({ + * question: "How many employees are there?", + * }); + * ``` + */ + static assign(mapping) { + return new RunnableAssign(new RunnableMap({ steps: mapping })); } } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js + @@ -103666,1279 +113886,1316 @@ class RunnableWithMessageHistory extends RunnableBinding { -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js /** - * Abstract base class for parsing the output of a Large Language Model - * (LLM) call. It provides methods for parsing the result of an LLM call - * and invoking the parser with a given input. + * Creates a transform stream for encoding chat message chunks. + * @deprecated Use {@link BytesOutputParser} instead + * @returns A TransformStream instance that encodes chat message chunks. */ -class BaseLLMOutputParser extends Runnable { - /** - * Parses the result of an LLM call with a given prompt. By default, it - * simply calls `parseResult`. - * @param generations The generations from an LLM call. - * @param _prompt The prompt used in the LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - _baseMessageToString(message) { - return typeof message.content === "string" - ? message.content - : this._baseMessageContentToString(message.content); - } - _baseMessageContentToString(content) { - return JSON.stringify(content); - } - /** - * Calls the parser with a given input and optional configuration options. - * If the input is a string, it creates a generation with the input as - * text and calls `parseResult`. If the input is a `BaseMessage`, it - * creates a generation with the input as a message and the content of the - * input as text, and then calls `parseResult`. - * @param input The input to the parser, which can be a string or a `BaseMessage`. - * @param options Optional configuration options. - * @returns A promise of the parsed output. - */ - async invoke(input, options) { - if (typeof input === "string") { - return this._callWithConfig(async (input, options) => this.parseResult([{ text: input }], options?.callbacks), input, { ...options, runType: "parser" }); - } - else { - return this._callWithConfig(async (input, options) => this.parseResult([ - { - message: input, - text: this._baseMessageToString(input), - }, - ], options?.callbacks), input, { ...options, runType: "parser" }); - } - } +function createChatMessageChunkEncoderStream() { + const textEncoder = new TextEncoder(); + return new TransformStream({ + transform(chunk, controller) { + controller.enqueue(textEncoder.encode(typeof chunk.content === "string" + ? chunk.content + : JSON.stringify(chunk.content))); + }, + }); } -/** - * Class to parse the output of an LLM call. - */ -class BaseOutputParser extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); - } - /** - * Return the string type key uniquely identifying this class of parser - */ - _type() { - throw new Error("_type not implemented"); +function _formatForTracing(messages) { + const messagesToTrace = []; + for (const message of messages) { + let messageToTrace = message; + if (Array.isArray(message.content)) { + for (let idx = 0; idx < message.content.length; idx++) { + const block = message.content[idx]; + if (isURLContentBlock(block) || isBase64ContentBlock(block)) { + if (messageToTrace === message) { + // Also shallow-copy content + // eslint-disable-next-line @typescript-eslint/no-explicit-any + messageToTrace = new message.constructor({ + ...messageToTrace, + content: [ + ...message.content.slice(0, idx), + convertToOpenAIImageBlock(block), + ...message.content.slice(idx + 1), + ], + }); + } + } + } + } + messagesToTrace.push(messageToTrace); } + return messagesToTrace; } /** - * Exception that output parsers should raise to signify a parsing error. - * - * This exists to differentiate parsing errors from other code or execution errors - * that also may arise inside the output parser. OutputParserExceptions will be - * available to catch and handle in ways to fix the parsing error, while other - * errors will be raised. - * - * @param message - The error that's being re-raised or an error message. - * @param llmOutput - String model output which is error-ing. - * @param observation - String explanation of error which can be passed to a - * model to try and remediate the issue. - * @param sendToLLM - Whether to send the observation and llm_output back to an Agent - * after an OutputParserException has been raised. This gives the underlying - * model driving the agent the context that the previous output was improperly - * structured, in the hopes that it will update the output to the correct - * format. + * Base class for chat models. It extends the BaseLanguageModel class and + * provides methods for generating chat based on input messages. */ -class OutputParserException extends Error { - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - Object.defineProperty(this, "llmOutput", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "observation", { +class BaseChatModel extends BaseLanguageModel { + constructor(fields) { + super(fields); + // Only ever instantiated in main LangChain + Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: ["langchain", "chat_models", this._llmType()] }); - Object.defineProperty(this, "sendToLLM", { + Object.defineProperty(this, "disableStreaming", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: false }); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === undefined || llmOutput === undefined) { - throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); - } - } - addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js -function deep_compare_strict_deepCompareStrict(a, b) { - const typeofa = typeof a; - if (typeofa !== typeof b) { - return false; + _separateRunnableConfigFromCallOptionsCompat(options) { + // For backwards compat, keep `signal` in both runnableConfig and callOptions + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - const length = a.length; - if (length !== b.length) { - return false; + /** + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = BaseChatModel._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + const chatGeneration = result.generations[0][0]; + // TODO: Remove cast after figuring out inheritance + return chatGeneration.message; + } + // eslint-disable-next-line require-yield + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); + } + async *_streamIterator(input, options) { + // Subclass check required to avoid double callbacks with default implementation + if (this._streamResponseChunks === + BaseChatModel.prototype._streamResponseChunks || + this.disableStreaming) { + yield this.invoke(input, options); } - for (let i = 0; i < length; i++) { - if (!deep_compare_strict_deepCompareStrict(a[i], b[i])) { - return false; + else { + const prompt = BaseChatModel._convertInputToPromptValue(input); + const messages = prompt.toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const inheritableMetadata = { + ...runnableConfig.metadata, + ...this.getLsParams(callOptions), + }; + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + batch_size: 1, + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, undefined, extra, undefined, undefined, runnableConfig.runName); + let generationChunk; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let llmOutput; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata, + }; + yield chunk.message; + if (!generationChunk) { + generationChunk = chunk; + } + else { + generationChunk = generationChunk.concat(chunk); + } + if (isAIMessageChunk(chunk.message) && + chunk.message.usage_metadata !== undefined) { + llmOutput = { + tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens, + }, + }; + } + } + } + catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + // TODO: Remove cast after figuring out inheritance + generations: [[generationChunk]], + llmOutput, + }))); } - return true; } - if (typeofa === 'object') { - if (!a || !b) { - return a === b; - } - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - const length = aKeys.length; - if (length !== bKeys.length) { - return false; + getLsParams(options) { + const providerName = this.getName().startsWith("Chat") + ? this.getName().replace("Chat", "") + : this.getName(); + return { + ls_model_type: "chat", + ls_stop: options.stop, + ls_provider: providerName, + }; + } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + let runManagers; + if (startedRunManagers !== undefined && + startedRunManagers.length === baseMessages.length) { + runManagers = startedRunManagers; } - for (const k of aKeys) { - if (!deep_compare_strict_deepCompareStrict(a[k], b[k])) { - return false; - } + else { + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions), + }; + // create callback manager and start run + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1, + }; + runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); } - return true; - } - return a === b; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js - -const schemaKeyword = { - additionalItems: true, - unevaluatedItems: true, - items: true, - contains: true, - additionalProperties: true, - unevaluatedProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true -}; -const schemaArrayKeyword = { - prefixItems: true, - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; -const schemaMapKeyword = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependentSchemas: true -}; -const ignoredKeyword = { - id: true, - $id: true, - $ref: true, - $schema: true, - $anchor: true, - $vocabulary: true, - $comment: true, - default: true, - enum: true, - const: true, - required: true, - type: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; -let initialBaseURI = typeof self !== 'undefined' && - self.location && - self.location.origin !== 'null' - ? - new URL(self.location.origin + self.location.pathname + location.search) - : new URL('https://github.com/cfworker'); -function dereference_dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { - if (schema && typeof schema === 'object' && !Array.isArray(schema)) { - const id = schema.$id || schema.id; - if (id) { - const url = new URL(id, baseURI.href); - if (url.hash.length > 1) { - lookup[url.href] = schema; + const generations = []; + const llmOutputs = []; + // Even if stream is not explicitly called, check if model is implicitly + // called from streamEvents() or streamLog() to get all streamed events. + // Bail out if _streamResponseChunks not overridden + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + if (hasStreamingHandler && + !this.disableStreaming && + baseMessages.length === 1 && + this._streamResponseChunks !== + BaseChatModel.prototype._streamResponseChunks) { + try { + const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); + let aggregated; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let llmOutput; + for await (const chunk of stream) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + chunk.message._updateId(`run-${runId}`); + } + if (aggregated === undefined) { + aggregated = chunk; + } + else { + aggregated = concat(aggregated, chunk); + } + if (isAIMessageChunk(chunk.message) && + chunk.message.usage_metadata !== undefined) { + llmOutput = { + tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens, + }, + }; + } + } + if (aggregated === undefined) { + throw new Error("Received empty response from chat model call."); + } + generations.push([aggregated]); + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput, + }); } - else { - url.hash = ''; - if (basePointer === '') { - baseURI = url; + catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + } + else { + // generate results + const results = await Promise.allSettled(baseMessages.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers?.[i]))); + // handle results + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + for (const generation of result.generations) { + if (generation.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) + generation.message._updateId(`run-${runId}`); + } + generation.message.response_metadata = { + ...generation.generationInfo, + ...generation.message.response_metadata, + }; + } + if (result.generations.length === 1) { + result.generations[0].message.response_metadata = { + ...result.llmOutput, + ...result.generations[0].message.response_metadata, + }; + } + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput, + }); } else { - dereference_dereference(schema, lookup, baseURI); + // status === "rejected" + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); } - } + })); } - } - else if (schema !== true && schema !== false) { - return lookup; - } - const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); - if (lookup[schemaURI] !== undefined) { - throw new Error(`Duplicate schema URI "${schemaURI}".`); - } - lookup[schemaURI] = schema; - if (schema === true || schema === false) { - return lookup; - } - if (schema.__absolute_uri__ === undefined) { - Object.defineProperty(schema, '__absolute_uri__', { - enumerable: false, - value: schemaURI - }); - } - if (schema.$ref && schema.__absolute_ref__ === undefined) { - const url = new URL(schema.$ref, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { - const url = new URL(schema.$recursiveRef, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_recursive_ref__', { - enumerable: false, - value: url.href + // create combined output + const output = { + generations, + llmOutput: llmOutputs.length + ? this._combineLLMOutput?.(...llmOutputs) + : undefined, + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers + ? { runIds: runManagers?.map((manager) => manager.runId) } + : undefined, + configurable: true, }); + return output; } - if (schema.$anchor) { - const url = new URL('#' + schema.$anchor, baseURI.href); - lookup[url.href] = schema; - } - for (let key in schema) { - if (ignoredKeyword[key]) { - continue; - } - const keyBase = `${basePointer}/${encodePointer(key)}`; - const subSchema = schema[key]; - if (Array.isArray(subSchema)) { - if (schemaArrayKeyword[key]) { - const length = subSchema.length; - for (let i = 0; i < length; i++) { - dereference_dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }) { + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions), + }; + // create callback manager and start run + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1, + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, undefined, extra, undefined, undefined, handledOptions.runName); + // generate results + const missingPromptIndices = []; + const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache.lookup(prompt, llmStringKey); + if (result == null) { + missingPromptIndices.push(index); + } + return result; + })); + // Map run managers to the results before filtering out null results + // Null results are just absent from the cache. + const cachedResults = results + .map((result, index) => ({ result, runManager: runManagers?.[index] })) + .filter(({ result }) => (result.status === "fulfilled" && result.value != null) || + result.status === "rejected"); + // Handle results and call run managers + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result) => { + if ("message" in result && + isBaseMessage(result.message) && + isAIMessage(result.message)) { + // eslint-disable-next-line no-param-reassign + result.message.usage_metadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0, + }; + } + // eslint-disable-next-line no-param-reassign + result.generationInfo = { + ...result.generationInfo, + tokenUsage: {}, + }; + return result; + }); + if (result.length) { + await runManager?.handleLLMNewToken(result[0].text); } + return runManager?.handleLLMEnd({ + generations: [result], + }, undefined, undefined, undefined, { + cached: true, + }); } - } - else if (schemaMapKeyword[key]) { - for (let subKey in subSchema) { - dereference_dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + else { + // status === "rejected" + await runManager?.handleLLMError(promiseResult.reason, undefined, undefined, undefined, { + cached: true, + }); + return Promise.reject(promiseResult.reason); } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers, + }; + // This defines RUN_KEY as a non-enumerable property on the output object + // so that it is not serialized when the output is stringified, and so that + // it isnt included when listing the keys of the output object. + Object.defineProperty(output, RUN_KEY, { + value: runManagers + ? { runIds: runManagers?.map((manager) => manager.runId) } + : undefined, + configurable: true, + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + // parse call options + let parsedOptions; + if (Array.isArray(options)) { + parsedOptions = { stop: options }; } else { - dereference_dereference(subSchema, lookup, baseURI, keyBase); + parsedOptions = options; } + const baseMessages = messages.map((messageList) => messageList.map(coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) { + return this._generateUncached(baseMessages, callOptions, runnableConfig); + } + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + messages: baseMessages, + cache, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig, + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== undefined + ? missingPromptIndices.map((i) => startedRunManagers?.[i]) + : undefined); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + // Join all content into one string for the prompt index + const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { generations, llmOutput }; } - return lookup; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js -const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; -const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; -const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; -const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; -const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; -const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; -const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; -const FASTDATE = /^\d\d\d\d-[0-1]\d-[0-3]\d$/; -const FASTTIME = /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i; -const FASTDATETIME = /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i; -const FASTURIREFERENCE = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i; -const EMAIL = (input) => { - if (input[0] === '"') - return false; - const [name, host, ...rest] = input.split('@'); - if (!name || - !host || - rest.length !== 0 || - name.length > 64 || - host.length > 253) - return false; - if (name[0] === '.' || name.endsWith('.') || name.includes('..')) - return false; - if (!/^[a-z0-9.-]+$/i.test(host) || - !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) - return false; - return host - .split('.') - .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); -}; -const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; -const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; -const DURATION = (input) => input.length > 1 && - input.length < 80 && - (/^P\d+([.,]\d+)?W$/.test(input) || - (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && - /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); -function bind(r) { - return r.test.bind(r); -} -const fullFormat = { - date, - time: time.bind(undefined, false), - 'date-time': date_time, - duration: DURATION, - uri, - 'uri-reference': bind(URIREF), - 'uri-template': bind(URITEMPLATE), - url: bind(URL_), - email: EMAIL, - hostname: bind(HOSTNAME), - ipv4: bind(IPV4), - ipv6: bind(IPV6), - regex: regex, - uuid: bind(UUID), - 'json-pointer': bind(JSON_POINTER), - 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), - 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) -}; -const format_fastFormat = { - ...fullFormat, - date: bind(FASTDATE), - time: bind(FASTTIME), - 'date-time': bind(FASTDATETIME), - 'uri-reference': bind(FASTURIREFERENCE) -}; -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function date(str) { - const matches = str.match(DATE); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return (month >= 1 && - month <= 12 && - day >= 1 && - day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); -} -function time(full, str) { - const matches = str.match(TIME); - if (!matches) - return false; - const hour = +matches[1]; - const minute = +matches[2]; - const second = +matches[3]; - const timeZone = !!matches[5]; - return (((hour <= 23 && minute <= 59 && second <= 59) || - (hour == 23 && minute == 59 && second == 60)) && - (!full || timeZone)); -} -const DATE_TIME_SEPARATOR = /t|\s/i; -function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); -} -const NOT_URI_FRAGMENT = /\/|:/; -const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); -} -const Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str, 'u'); - return true; - } - catch (e) { - return false; + /** + * Get the parameters used to invoke the model + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + invocationParams(_options) { + return {}; } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js -var OutputFormat; -(function (OutputFormat) { - OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; - OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; - OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; -})(OutputFormat || (OutputFormat = {})); - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js - - - - - -function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { - if (schema === true) { - return { valid: true, errors: [] }; + _modelType() { + return "base_chat_model"; } - if (schema === false) { + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { return { - valid: false, - errors: [ - { - instanceLocation, - keyword: 'false', - keywordLocation: instanceLocation, - error: 'False boolean schema.' - } - ] + ...this.invocationParams(), + _type: this._llmType(), + _model: this._modelType(), }; } - const rawInstanceType = typeof instance; - let instanceType; - switch (rawInstanceType) { - case 'boolean': - case 'number': - case 'string': - instanceType = rawInstanceType; - break; - case 'object': - if (instance === null) { - instanceType = 'null'; - } - else if (Array.isArray(instance)) { - instanceType = 'array'; - } - else { - instanceType = 'object'; - } - break; - default: - throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); } - const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; - const errors = []; - if ($recursiveAnchor === true && recursiveAnchor === null) { - recursiveAnchor = schema; + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Makes a single call to the chat model. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async call(messages, options, callbacks) { + const result = await this.generate([messages.map(coerceMessageLikeToMessage)], options, callbacks); + const generations = result.generations; + return generations[0][0].message; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Makes a single call to the chat model with a prompt value. + * @param promptValue The value of the prompt. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async callPrompt(promptValue, options, callbacks) { + const promptMessages = promptValue.toChatMessages(); + return this.call(promptMessages, options, callbacks); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Predicts the next message based on the input messages. + * @param messages An array of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a BaseMessage. + */ + async predictMessages(messages, options, callbacks) { + return this.call(messages, options, callbacks); } - if ($recursiveRef === '#') { - const refSchema = recursiveAnchor === null - ? lookup[__absolute_recursive_ref__] - : recursiveAnchor; - const keywordLocation = `${schemaLocation}/$recursiveRef`; - const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$recursiveRef', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); + /** + * @deprecated Use .invoke() instead. Will be removed in 0.2.0. + * + * Predicts the next message based on a text input. + * @param text The text input. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to a string. + */ + async predict(text, options, callbacks) { + const message = new human_HumanMessage(text); + const result = await this.call([message], options, callbacks); + if (typeof result.content !== "string") { + throw new Error("Cannot use predict when output is not a string."); } + return result.content; } - if ($ref !== undefined) { - const uri = __absolute_ref__ || $ref; - const refSchema = lookup[uri]; - if (refSchema === undefined) { - let message = `Unresolved $ref "${$ref}".`; - if (__absolute_ref__ && __absolute_ref__ !== $ref) { - message += ` Absolute URI "${__absolute_ref__}".`; - } - message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; - throw new Error(message); + withStructuredOutput(outputSchema, config) { + if (typeof this.bindTools !== "function") { + throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); } - const keywordLocation = `${schemaLocation}/$ref`; - const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$ref', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); + if (config?.strict) { + throw new Error(`"strict" mode is not supported for this model by default.`); } - if (draft === '4' || draft === '7') { - return { valid: errors.length === 0, errors }; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const schema = outputSchema; + const name = config?.name; + const description = getSchemaDescription(schema) ?? "A function available to call."; + const method = config?.method; + const includeRaw = config?.includeRaw; + if (method === "jsonMode") { + throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); } - } - if (Array.isArray($type)) { - let length = $type.length; - let valid = false; - for (let i = 0; i < length; i++) { - if (instanceType === $type[i] || - ($type[i] === 'integer' && - instanceType === 'number' && - instance % 1 === 0 && - instance === instance)) { - valid = true; - break; - } + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema)) { + tools = [ + { + type: "function", + function: { + name: functionName, + description, + parameters: json_schema_toJsonSchema(schema), + }, + }, + ]; } - if (!valid) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` - }); + else { + if ("name" in schema) { + functionName = schema.name; + } + tools = [ + { + type: "function", + function: { + name: functionName, + description, + parameters: schema, + }, + }, + ]; } - } - else if ($type === 'integer') { - if (instanceType !== 'number' || instance % 1 || instance !== instance) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + const llm = this.bindTools(tools); + const outputParser = base_RunnableLambda.from((input) => { + if (!input.tool_calls || input.tool_calls.length === 0) { + throw new Error("No tool calls found in the response."); + } + const toolCall = input.tool_calls.find((tc) => tc.name === functionName); + if (!toolCall) { + throw new Error(`No tool call found with name ${functionName}.`); + } + return toolCall.args; + }); + if (!includeRaw) { + return llm.pipe(outputParser).withConfig({ + runName: "StructuredOutput", }); } - } - else if ($type !== undefined && instanceType !== $type) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + const parserAssign = RunnablePassthrough.assign({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + parsed: (input, config) => outputParser.invoke(input.raw, config), + }); + const parserNone = RunnablePassthrough.assign({ + parsed: () => null, + }); + const parsedWithFallback = parserAssign.withFallbacks({ + fallbacks: [parserNone], + }); + return RunnableSequence.from([ + { + raw: llm, + }, + parsedWithFallback, + ]).withConfig({ + runName: "StructuredOutputRunnable", }); } - if ($const !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!deepCompareStrict(instance, $const)) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } - } - else if (instance !== $const) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); +} +/** + * An abstract class that extends BaseChatModel and provides a simple + * implementation of _generate. + */ +class SimpleChatModel extends (/* unused pure expression or super */ null && (BaseChatModel)) { + async _generate(messages, options, runManager) { + const text = await this._call(messages, options, runManager); + const message = new AIMessage(text); + if (typeof message.content !== "string") { + throw new Error("Cannot generate with a simple chat model when output is not a string."); } + return { + generations: [ + { + text: message.content, + message, + }, + ], + }; } - if ($enum !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!$enum.some(value => deepCompareStrict(instance, value))) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - else if (!$enum.some(value => instance === value)) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/language_models/chat_models.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/outputs.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/async_caller.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js + + +/** + * A runnable that routes to a set of runnables based on Input['key']. + * Returns the output of the selected runnable. + * @example + * ```typescript + * import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; + * + * const router = new RouterRunnable({ + * runnables: { + * toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), + * reverseText: RunnableLambda.from((text: string) => + * text.split("").reverse().join("") + * ), + * }, + * }); + * + * // Invoke the 'reverseText' runnable + * const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); + * + * // "dlroW olleH" + * + * // Invoke the 'toUpperCase' runnable + * const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); + * + * // "HELLO WORLD" + * ``` + */ +class RouterRunnable extends Runnable { + static lc_name() { + return "RouterRunnable"; } - if ($not !== undefined) { - const keywordLocation = `${schemaLocation}/not`; - const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); - if (result.valid) { - errors.push({ - instanceLocation, - keyword: 'not', - keywordLocation, - error: 'Instance matched "not" schema.' - }); - } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "runnables", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnables = fields.runnables; } - let subEvaluateds = []; - if ($anyOf !== undefined) { - const keywordLocation = `${schemaLocation}/anyOf`; - const errorsLength = errors.length; - let anyValid = false; - for (let i = 0; i < $anyOf.length; i++) { - const subSchema = $anyOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - anyValid = anyValid || result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - } - if (anyValid) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'anyOf', - keywordLocation, - error: 'Instance does not match any subschemas.' - }); + async invoke(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) { + throw new Error(`No runnable associated with key "${key}".`); } + return runnable.invoke(actualInput, ensureConfig(options)); } - if ($allOf !== undefined) { - const keywordLocation = `${schemaLocation}/allOf`; - const errorsLength = errors.length; - let allValid = true; - for (let i = 0; i < $allOf.length; i++) { - const subSchema = $allOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - allValid = allValid && result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - } - if (allValid) { - errors.length = errorsLength; + async batch(inputs, options, batchOptions) { + const keys = inputs.map((input) => input.key); + const actualInputs = inputs.map((input) => input.input); + const missingKey = keys.find((key) => this.runnables[key] === undefined); + if (missingKey !== undefined) { + throw new Error(`One or more keys do not have a corresponding runnable.`); } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'allOf', - keywordLocation, - error: `Instance does not match every subschema.` - }); + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; + const batchResults = []; + for (let i = 0; i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs + .slice(i, i + batchSize) + .map((actualInput, i) => runnables[i].invoke(actualInput, optionsList[i])); + const batchResult = await Promise.all(batchPromises); + batchResults.push(batchResult); } + return batchResults.flat(); } - if ($oneOf !== undefined) { - const keywordLocation = `${schemaLocation}/oneOf`; - const errorsLength = errors.length; - const matches = $oneOf.filter((subSchema, i) => { - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - return result.valid; - }).length; - if (matches === 1) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'oneOf', - keywordLocation, - error: `Instance does not match exactly one subschema (${matches} matches).` - }); + async stream(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === undefined) { + throw new Error(`No runnable associated with key "${key}".`); } + return runnable.stream(actualInput, options); } - if (instanceType === 'object' || instanceType === 'array') { - Object.assign(evaluated, ...subEvaluateds); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js + + + +/** + * Class that represents a runnable branch. The RunnableBranch is + * initialized with an array of branches and a default branch. When invoked, + * it evaluates the condition of each branch in order and executes the + * corresponding branch if the condition is true. If none of the conditions + * are true, it executes the default branch. + * @example + * ```typescript + * const branch = RunnableBranch.from([ + * [ + * (x: { topic: string; question: string }) => + * x.topic.toLowerCase().includes("anthropic"), + * anthropicChain, + * ], + * [ + * (x: { topic: string; question: string }) => + * x.topic.toLowerCase().includes("langchain"), + * langChainChain, + * ], + * generalChain, + * ]); + * + * const fullChain = RunnableSequence.from([ + * { + * topic: classificationChain, + * question: (input: { question: string }) => input.question, + * }, + * branch, + * ]); + * + * const result = await fullChain.invoke({ + * question: "how do I use LangChain?", + * }); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +class RunnableBranch extends Runnable { + static lc_name() { + return "RunnableBranch"; } - if ($if !== undefined) { - const keywordLocation = `${schemaLocation}/if`; - const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; - if (conditionResult) { - if ($then !== undefined) { - const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); - if (!thenResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "then" schema.` - }, ...thenResult.errors); - } - } - } - else if ($else !== undefined) { - const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); - if (!elseResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "else" schema.` - }, ...elseResult.errors); - } + constructor(fields) { + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "runnables"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "default", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "branches", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.branches = fields.branches; + this.default = fields.default; + } + /** + * Convenience method for instantiating a RunnableBranch from + * RunnableLikes (objects, functions, or Runnables). + * + * Each item in the input except for the last one should be a + * tuple with two items. The first is a "condition" RunnableLike that + * returns "true" if the second RunnableLike in the tuple should run. + * + * The final item in the input should be a RunnableLike that acts as a + * default branch if no other branches match. + * + * @example + * ```ts + * import { RunnableBranch } from "@langchain/core/runnables"; + * + * const branch = RunnableBranch.from([ + * [(x: number) => x > 0, (x: number) => x + 1], + * [(x: number) => x < 0, (x: number) => x - 1], + * (x: number) => x + * ]); + * ``` + * @param branches An array where the every item except the last is a tuple of [condition, runnable] + * pairs. The last item is a default runnable which is invoked if no other condition matches. + * @returns A new RunnableBranch. + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static from(branches) { + if (branches.length < 1) { + throw new Error("RunnableBranch requires at least one branch"); } + const branchLikes = branches.slice(0, -1); + const coercedBranches = branchLikes.map(([condition, runnable]) => [ + _coerceToRunnable(condition), + _coerceToRunnable(runnable), + ]); + const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); + return new this({ + branches: coercedBranches, + default: defaultBranch, + }); } - if (instanceType === 'object') { - if ($required !== undefined) { - for (const key of $required) { - if (!(key in instance)) { - errors.push({ - instanceLocation, - keyword: 'required', - keywordLocation: `${schemaLocation}/required`, - error: `Instance does not have required property "${key}".` - }); - } + async _invoke(input, config, runManager) { + let result; + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`condition:${i + 1}`), + })); + if (conditionValue) { + result = await branchRunnable.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`branch:${i + 1}`), + })); + break; } } - const keys = Object.keys(instance); - if ($minProperties !== undefined && keys.length < $minProperties) { - errors.push({ - instanceLocation, - keyword: 'minProperties', - keywordLocation: `${schemaLocation}/minProperties`, - error: `Instance does not have at least ${$minProperties} properties.` - }); - } - if ($maxProperties !== undefined && keys.length > $maxProperties) { - errors.push({ - instanceLocation, - keyword: 'maxProperties', - keywordLocation: `${schemaLocation}/maxProperties`, - error: `Instance does not have at least ${$maxProperties} properties.` - }); - } - if ($propertyNames !== undefined) { - const keywordLocation = `${schemaLocation}/propertyNames`; - for (const key in instance) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'propertyNames', - keywordLocation, - error: `Property name "${key}" does not match schema.` - }, ...result.errors); - } - } + if (!result) { + result = await this.default.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild("branch:default"), + })); } - if ($dependentRequired !== undefined) { - const keywordLocation = `${schemaLocation}/dependantRequired`; - for (const key in $dependentRequired) { - if (key in instance) { - const required = $dependentRequired[key]; - for (const dependantKey of required) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependentRequired', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); + return result; + } + async invoke(input, config = {}) { + return this._callWithConfig(this._invoke, input, config); + } + async *_streamIterator(input, config) { + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, undefined, undefined, undefined, config?.runName); + let finalOutput; + let finalOutputSupported = true; + let stream; + try { + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, patchConfig(config, { + callbacks: runManager?.getChild(`condition:${i + 1}`), + })); + if (conditionValue) { + stream = await branchRunnable.stream(input, patchConfig(config, { + callbacks: runManager?.getChild(`branch:${i + 1}`), + })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; + } + else { + try { + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = undefined; + finalOutputSupported = false; + } + } } } + break; } } - } - if ($dependentSchemas !== undefined) { - for (const key in $dependentSchemas) { - const keywordLocation = `${schemaLocation}/dependentSchemas`; - if (key in instance) { - const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependentSchemas', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } - } - if ($dependencies !== undefined) { - const keywordLocation = `${schemaLocation}/dependencies`; - for (const key in $dependencies) { - if (key in instance) { - const propsOrSchema = $dependencies[key]; - if (Array.isArray(propsOrSchema)) { - for (const dependantKey of propsOrSchema) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } + if (stream === undefined) { + stream = await this.default.stream(input, patchConfig(config, { + callbacks: runManager?.getChild("branch:default"), + })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) { + if (finalOutput === undefined) { + finalOutput = chunk; } - } - else { - const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); + else { + try { + finalOutput = concat(finalOutput, chunk); + } + catch (e) { + finalOutput = undefined; + finalOutputSupported = false; + } } } } } } - const thisEvaluated = Object.create(null); - let stop = false; - if ($properties !== undefined) { - const keywordLocation = `${schemaLocation}/properties`; - for (const key in $properties) { - if (!(key in instance)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'properties', - keywordLocation, - error: `Property "${key}" does not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if (!stop && $patternProperties !== undefined) { - const keywordLocation = `${schemaLocation}/patternProperties`; - for (const pattern in $patternProperties) { - const regex = new RegExp(pattern, 'u'); - const subSchema = $patternProperties[pattern]; - for (const key in instance) { - if (!regex.test(key)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'patternProperties', - keywordLocation, - error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` - }, ...result.errors); - } - } - } - } - if (!stop && $additionalProperties !== undefined) { - const keywordLocation = `${schemaLocation}/additionalProperties`; - for (const key in instance) { - if (thisEvaluated[key]) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalProperties', - keywordLocation, - error: `Property "${key}" does not match additional properties schema.` - }, ...result.errors); - } - } - } - else if (!stop && $unevaluatedProperties !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedProperties`; - for (const key in instance) { - if (!evaluated[key]) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - errors.push({ - instanceLocation, - keyword: 'unevaluatedProperties', - keywordLocation, - error: `Property "${key}" does not match unevaluated properties schema.` - }, ...result.errors); - } - } - } + catch (e) { + await runManager?.handleChainError(e); + throw e; } + await runManager?.handleChainEnd(finalOutput ?? {}); } - else if (instanceType === 'array') { - if ($maxItems !== undefined && instance.length > $maxItems) { - errors.push({ - instanceLocation, - keyword: 'maxItems', - keywordLocation: `${schemaLocation}/maxItems`, - error: `Array has too many items (${instance.length} > ${$maxItems}).` - }); - } - if ($minItems !== undefined && instance.length < $minItems) { - errors.push({ - instanceLocation, - keyword: 'minItems', - keywordLocation: `${schemaLocation}/minItems`, - error: `Array has too few items (${instance.length} < ${$minItems}).` - }); - } - const length = instance.length; - let i = 0; - let stop = false; - if ($prefixItems !== undefined) { - const keywordLocation = `${schemaLocation}/prefixItems`; - const length2 = Math.min($prefixItems.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'prefixItems', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js + + + +/** + * Wraps a LCEL chain and manages history. It appends input messages + * and chain outputs as history, and adds the current history messages to + * the chain input. + * @example + * ```typescript + * // yarn add @langchain/anthropic @langchain/community @upstash/redis + * + * import { + * ChatPromptTemplate, + * MessagesPlaceholder, + * } from "@langchain/core/prompts"; + * import { ChatAnthropic } from "@langchain/anthropic"; + * import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; + * // For demos, you can also use an in-memory store: + * // import { ChatMessageHistory } from "langchain/stores/message/in_memory"; + * + * const prompt = ChatPromptTemplate.fromMessages([ + * ["system", "You're an assistant who's good at {ability}"], + * new MessagesPlaceholder("history"), + * ["human", "{question}"], + * ]); + * + * const chain = prompt.pipe(new ChatAnthropic({})); + * + * const chainWithHistory = new RunnableWithMessageHistory({ + * runnable: chain, + * getMessageHistory: (sessionId) => + * new UpstashRedisChatMessageHistory({ + * sessionId, + * config: { + * url: process.env.UPSTASH_REDIS_REST_URL!, + * token: process.env.UPSTASH_REDIS_REST_TOKEN!, + * }, + * }), + * inputMessagesKey: "question", + * historyMessagesKey: "history", + * }); + * + * const result = await chainWithHistory.invoke( + * { + * ability: "math", + * question: "What does cosine mean?", + * }, + * { + * configurable: { + * sessionId: "some_string_identifying_a_user", + * }, + * } + * ); + * + * const result2 = await chainWithHistory.invoke( + * { + * ability: "math", + * question: "What's its inverse?", + * }, + * { + * configurable: { + * sessionId: "some_string_identifying_a_user", + * }, + * } + * ); + * ``` + */ +class RunnableWithMessageHistory extends RunnableBinding { + constructor(fields) { + let historyChain = base_RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); + const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; + if (messagesKey) { + historyChain = RunnablePassthrough.assign({ + [messagesKey]: historyChain, + }).withConfig({ runName: "insertHistory" }); } - if ($items !== undefined) { - const keywordLocation = `${schemaLocation}/items`; - if (Array.isArray($items)) { - const length2 = Math.min($items.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - else { - for (; i < length; i++) { - const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if (!stop && $additionalItems !== undefined) { - const keywordLocation = `${schemaLocation}/additionalItems`; - for (; i < length; i++) { - const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalItems', - keywordLocation, - error: `Items did not match additional items schema.` - }, ...result.errors); - } - } + const bound = historyChain + .pipe(fields.runnable.withListeners({ + onEnd: (run, config) => this._exitHistory(run, config ?? {}), + })) + .withConfig({ runName: "RunnableWithMessageHistory" }); + const config = fields.config ?? {}; + super({ + ...fields, + config, + bound, + }); + Object.defineProperty(this, "runnable", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "historyMessagesKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "getMessageHistory", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.runnable = fields.runnable; + this.getMessageHistory = fields.getMessageHistory; + this.inputMessagesKey = fields.inputMessagesKey; + this.outputMessagesKey = fields.outputMessagesKey; + this.historyMessagesKey = fields.historyMessagesKey; + } + _getInputMessages( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + inputValue) { + let parsedInputValue; + if (typeof inputValue === "object" && + !Array.isArray(inputValue) && + !isBaseMessage(inputValue)) { + let key; + if (this.inputMessagesKey) { + key = this.inputMessagesKey; } - } - if ($contains !== undefined) { - if (length === 0 && $minContains === undefined) { - errors.push({ - instanceLocation, - keyword: 'contains', - keywordLocation: `${schemaLocation}/contains`, - error: `Array is empty. It must contain at least one item matching the schema.` - }); + else if (Object.keys(inputValue).length === 1) { + key = Object.keys(inputValue)[0]; } - else if ($minContains !== undefined && length < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array has less items (${length}) than minContains (${$minContains}).` - }); + else { + key = "input"; + } + if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) { + parsedInputValue = inputValue[key][0]; } else { - const keywordLocation = `${schemaLocation}/contains`; - const errorsLength = errors.length; - let contained = 0; - for (let j = 0; j < length; j++) { - const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); - if (result.valid) { - evaluated[j] = true; - contained++; - } - else { - errors.push(...result.errors); - } - } - if (contained >= ($minContains || 0)) { - errors.length = errorsLength; - } - if ($minContains === undefined && - $maxContains === undefined && - contained === 0) { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'contains', - keywordLocation, - error: `Array does not contain item matching schema.` - }); - } - else if ($minContains !== undefined && contained < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` - }); - } - else if ($maxContains !== undefined && contained > $maxContains) { - errors.push({ - instanceLocation, - keyword: 'maxContains', - keywordLocation: `${schemaLocation}/maxContains`, - error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` - }); - } + parsedInputValue = inputValue[key]; } } - if (!stop && $unevaluatedItems !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedItems`; - for (i; i < length; i++) { - if (evaluated[i]) { - continue; - } - const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'unevaluatedItems', - keywordLocation, - error: `Items did not match unevaluated items schema.` - }, ...result.errors); - } - } + else { + parsedInputValue = inputValue; } - if ($uniqueItems) { - for (let j = 0; j < length; j++) { - const a = instance[j]; - const ao = typeof a === 'object' && a !== null; - for (let k = 0; k < length; k++) { - if (j === k) { - continue; - } - const b = instance[k]; - const bo = typeof b === 'object' && b !== null; - if (a === b || (ao && bo && deepCompareStrict(a, b))) { - errors.push({ - instanceLocation, - keyword: 'uniqueItems', - keywordLocation: `${schemaLocation}/uniqueItems`, - error: `Duplicate items at indexes ${j} and ${k}.` - }); - j = Number.MAX_SAFE_INTEGER; - k = Number.MAX_SAFE_INTEGER; - } - } - } + if (typeof parsedInputValue === "string") { + return [new human_HumanMessage(parsedInputValue)]; } - } - else if (instanceType === 'number') { - if (draft === '4') { - if ($minimum !== undefined && - (($exclusiveMinimum === true && instance <= $minimum) || - instance < $minimum)) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` - }); - } - if ($maximum !== undefined && - (($exclusiveMaximum === true && instance >= $maximum) || - instance > $maximum)) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` - }); - } + else if (Array.isArray(parsedInputValue)) { + return parsedInputValue; + } + else if (isBaseMessage(parsedInputValue)) { + return [parsedInputValue]; } else { - if ($minimum !== undefined && instance < $minimum) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$minimum}.` - }); + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); + } + } + _getOutputMessages( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + outputValue) { + let parsedOutputValue; + if (!Array.isArray(outputValue) && + !isBaseMessage(outputValue) && + typeof outputValue !== "string") { + let key; + if (this.outputMessagesKey !== undefined) { + key = this.outputMessagesKey; } - if ($maximum !== undefined && instance > $maximum) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$maximum}.` - }); + else if (Object.keys(outputValue).length === 1) { + key = Object.keys(outputValue)[0]; } - if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMinimum', - keywordLocation: `${schemaLocation}/exclusiveMinimum`, - error: `${instance} is less than ${$exclusiveMinimum}.` - }); + else { + key = "output"; } - if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMaximum', - keywordLocation: `${schemaLocation}/exclusiveMaximum`, - error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` - }); + // If you are wrapping a chat model directly + // The output is actually this weird generations object + if (outputValue.generations !== undefined) { + parsedOutputValue = outputValue.generations[0][0].message; } - } - if ($multipleOf !== undefined) { - const remainder = instance % $multipleOf; - if (Math.abs(0 - remainder) >= 1.1920929e-7 && - Math.abs($multipleOf - remainder) >= 1.1920929e-7) { - errors.push({ - instanceLocation, - keyword: 'multipleOf', - keywordLocation: `${schemaLocation}/multipleOf`, - error: `${instance} is not a multiple of ${$multipleOf}.` - }); + else { + parsedOutputValue = outputValue[key]; } } - } - else if (instanceType === 'string') { - const length = $minLength === undefined && $maxLength === undefined - ? 0 - : ucs2length(instance); - if ($minLength !== undefined && length < $minLength) { - errors.push({ - instanceLocation, - keyword: 'minLength', - keywordLocation: `${schemaLocation}/minLength`, - error: `String is too short (${length} < ${$minLength}).` - }); + else { + parsedOutputValue = outputValue; } - if ($maxLength !== undefined && length > $maxLength) { - errors.push({ - instanceLocation, - keyword: 'maxLength', - keywordLocation: `${schemaLocation}/maxLength`, - error: `String is too long (${length} > ${$maxLength}).` - }); + if (typeof parsedOutputValue === "string") { + return [new ai_AIMessage(parsedOutputValue)]; } - if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { - errors.push({ - instanceLocation, - keyword: 'pattern', - keywordLocation: `${schemaLocation}/pattern`, - error: `String does not match pattern.` - }); + else if (Array.isArray(parsedOutputValue)) { + return parsedOutputValue; } - if ($format !== undefined && - fastFormat[$format] && - !fastFormat[$format](instance)) { - errors.push({ - instanceLocation, - keyword: 'format', - keywordLocation: `${schemaLocation}/format`, - error: `String does not match format "${$format}".` - }); + else if (isBaseMessage(parsedOutputValue)) { + return [parsedOutputValue]; + } + else { + throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); } } - return { valid: errors.length === 0, errors }; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js - - -class Validator { - schema; - draft; - shortCircuit; - lookup; - constructor(schema, draft = '2019-09', shortCircuit = true) { - this.schema = schema; - this.draft = draft; - this.shortCircuit = shortCircuit; - this.lookup = dereference(schema); + async _enterHistory( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + input, kwargs) { + const history = kwargs?.configurable?.messageHistory; + const messages = await history.getMessages(); + if (this.historyMessagesKey === undefined) { + return messages.concat(this._getInputMessages(input)); + } + return messages; } - validate(instance) { - return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + async _exitHistory(run, config) { + const history = config.configurable?.messageHistory; + // Get input messages + let inputs; + // Chat model inputs are nested arrays + if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) { + inputs = run.inputs[0]; + } + else { + inputs = run.inputs; + } + let inputMessages = this._getInputMessages(inputs); + // If historic messages were prepended to the input messages, remove them to + // avoid adding duplicate messages to history. + if (this.historyMessagesKey === undefined) { + const existingMessages = await history.getMessages(); + inputMessages = inputMessages.slice(existingMessages.length); + } + // Get output messages + const outputValue = run.outputs; + if (!outputValue) { + throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); + } + const outputMessages = this._getOutputMessages(outputValue); + await history.addMessages([...inputMessages, ...outputMessages]); } - addSchema(schema, id) { - if (id) { - schema = { ...schema, $id: id }; + async _mergeConfig(...configs) { + const config = await super._mergeConfig(...configs); + // Extract sessionId + if (!config.configurable || !config.configurable.sessionId) { + const exampleInput = { + [this.inputMessagesKey ?? "input"]: "foo", + }; + const exampleConfig = { configurable: { sessionId: "123" } }; + throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\n` + + `eg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); } - dereference(schema, this.lookup); + // attach messageHistory + const { sessionId } = config.configurable; + config.configurable.messageHistory = await this.getMessageHistory(sessionId); + return config; } } -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js +/** + * Abstract base class for parsing the output of a Large Language Model + * (LLM) call. It provides methods for parsing the result of an LLM call + * and invoking the parser with a given input. + */ +class BaseLLMOutputParser extends Runnable { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + _baseMessageToString(message) { + return typeof message.content === "string" + ? message.content + : this._baseMessageContentToString(message.content); + } + _baseMessageContentToString(content) { + return JSON.stringify(content); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") { + return this._callWithConfig(async (input, options) => this.parseResult([{ text: input }], options?.callbacks), input, { ...options, runType: "parser" }); + } + else { + return this._callWithConfig(async (input, options) => this.parseResult([ + { + message: input, + text: this._baseMessageToString(input), + }, + ], options?.callbacks), input, { ...options, runType: "parser" }); + } + } +} +/** + * Class to parse the output of an LLM call. + */ +class BaseOutputParser extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +} +/** + * Exception that output parsers should raise to signify a parsing error. + * + * This exists to differentiate parsing errors from other code or execution errors + * that also may arise inside the output parser. OutputParserExceptions will be + * available to catch and handle in ways to fix the parsing error, while other + * errors will be raised. + * + * @param message - The error that's being re-raised or an error message. + * @param llmOutput - String model output which is error-ing. + * @param observation - String explanation of error which can be passed to a + * model to try and remediate the issue. + * @param sendToLLM - Whether to send the observation and llm_output back to an Agent + * after an OutputParserException has been raised. This gives the underlying + * model driving the agent the context that the previous output was improperly + * structured, in the hopes that it will update the output to the correct + * format. + */ +class OutputParserException extends Error { + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + Object.defineProperty(this, "llmOutput", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "observation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "sendToLLM", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === undefined || llmOutput === undefined) { + throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + } + addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); + } +} ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/transform.js @@ -105414,6 +115671,7 @@ class StringOutputParser extends BaseTransformOutputParser { + class StructuredOutputParser extends BaseOutputParser { static lc_name() { return "StructuredOutputParser"; @@ -105451,7 +115709,7 @@ class StructuredOutputParser extends BaseOutputParser { * @returns A new instance of StructuredOutputParser. */ static fromNamesAndDescriptions(schemas) { - const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)]))); + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); return new this(zodSchema); } /** @@ -105473,7 +115731,7 @@ Your output will be parsed and type-checked according to the provided schema ins Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: \`\`\`json -${JSON.stringify(zodToJsonSchema_zodToJsonSchema(this.schema))} +${JSON.stringify(json_schema_toJsonSchema(this.schema))} \`\`\` `; } @@ -105493,7 +115751,7 @@ ${JSON.stringify(zodToJsonSchema_zodToJsonSchema(this.schema))} return `"${escapedInsideQuotes}"`; }) .replace(/\n/g, ""); - return await this.schema.parseAsync(JSON.parse(escapedJson)); + return await interopParseAsync(this.schema, JSON.parse(escapedJson)); } catch (e) { throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); @@ -105513,7 +115771,7 @@ class JsonMarkdownStructuredOutputParser extends StructuredOutputParser { if (interpolationDepth < 1) { throw new Error("f string interpolation depth must be at least 1"); } - return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(zodToJsonSchema_zodToJsonSchema(this.schema)) + return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(json_schema_toJsonSchema(this.schema)) .replaceAll("{", "{".repeat(interpolationDepth)) .replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``; } @@ -105568,7 +115826,7 @@ class JsonMarkdownStructuredOutputParser extends StructuredOutputParser { return new this(schema); } static fromNamesAndDescriptions(schemas) { - const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)]))); + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); return new this(zodSchema); } } @@ -107371,6 +117629,7 @@ function parseXMLMarkdown(s) { + function json_output_tools_parsers_parseToolCall( // eslint-disable-next-line @typescript-eslint/no-explicit-any rawToolCall, options) { @@ -107577,12 +117836,12 @@ class JsonOutputKeyToolsParser extends JsonOutputToolsParser { if (this.zodSchema === undefined) { return result; } - const zodParsedResult = await this.zodSchema.safeParseAsync(result); + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); if (zodParsedResult.success) { return zodParsedResult.data; } else { - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(result, null, 2)); + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2)); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -107629,6 +117888,132 @@ class JsonOutputKeyToolsParser extends JsonOutputToolsParser { ;// CONCATENATED MODULE: ./node_modules/@langchain/core/runnables.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/json_schema.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/types.js + + +/** + * Confirm whether the inputted tool is an instance of `StructuredToolInterface`. + * + * @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`. + * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`. + */ +function isStructuredTool(tool) { + return (tool !== undefined && + Array.isArray(tool.lc_namespace)); +} +/** + * Confirm whether the inputted tool is an instance of `RunnableToolLike`. + * + * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`. + * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`. + */ +function isRunnableToolLike(tool) { + return (tool !== undefined && + Runnable.isRunnable(tool) && + "lc_name" in tool.constructor && + typeof tool.constructor.lc_name === "function" && + tool.constructor.lc_name() === "RunnableToolLike"); +} +/** + * Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`. + * + * @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`. + * @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`. + */ +function isStructuredToolParams(tool) { + return (!!tool && + typeof tool === "object" && + "name" in tool && + "schema" in tool && + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (isInteropZodSchema(tool.schema) || + (tool.schema != null && + typeof tool.schema === "object" && + "type" in tool.schema && + typeof tool.schema.type === "string" && + ["null", "boolean", "object", "array", "number", "string"].includes(tool.schema.type)))); +} +/** + * Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. + * It returns `is StructuredToolParams` since that is the most minimal interface of the three, + * while still containing the necessary properties to be passed to a LLM for tool calling. + * + * @param {unknown | undefined} tool The tool to check if it is a LangChain tool. + * @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool. + */ +function types_isLangChainTool(tool) { + return (isStructuredToolParams(tool) || + isRunnableToolLike(tool) || + // eslint-disable-next-line @typescript-eslint/no-explicit-any + isStructuredTool(tool)); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/function_calling.js + + +// These utility functions were moved to a more appropriate location, +// but we still export them here for backwards compatibility. + +/** + * Formats a `StructuredTool` or `RunnableToolLike` instance into a format + * that is compatible with OpenAI function calling. If `StructuredTool` or + * `RunnableToolLike` has a zod schema, the output will be converted into a + * JSON schema, which is then used as the parameters for the OpenAI tool. + * + * @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function. + * @returns {FunctionDefinition} The inputted tool in OpenAI function format. + */ +function convertToOpenAIFunction(tool, fields) { + // @TODO 0.3.0 Remove the `number` typing + const fieldsCopy = typeof fields === "number" ? undefined : fields; + return { + name: tool.name, + description: tool.description, + parameters: toJsonSchema(tool.schema), + // Do not include the `strict` field if it is `undefined`. + ...(fieldsCopy?.strict !== undefined ? { strict: fieldsCopy.strict } : {}), + }; +} +/** + * Formats a `StructuredTool` or `RunnableToolLike` instance into a + * format that is compatible with OpenAI tool calling. If `StructuredTool` or + * `RunnableToolLike` has a zod schema, the output will be converted into a + * JSON schema, which is then used as the parameters for the OpenAI tool. + * + * @param {StructuredToolInterface | Record | RunnableToolLike} tool The tool to convert to an OpenAI tool. + * @returns {ToolDefinition} The inputted tool in OpenAI tool format. + */ +function convertToOpenAITool( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +tool, fields) { + // @TODO 0.3.0 Remove the `number` typing + const fieldsCopy = typeof fields === "number" ? undefined : fields; + let toolDef; + if (isLangChainTool(tool)) { + toolDef = { + type: "function", + function: convertToOpenAIFunction(tool), + }; + } + else { + toolDef = tool; + } + if (fieldsCopy?.strict !== undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + toolDef.function.strict = fieldsCopy.strict; + } + return toolDef; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/function_calling.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/index.js + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/utils/types.js + ;// CONCATENATED MODULE: ./node_modules/@langchain/mistralai/dist/utils.js // Mistral enforces a specific pattern for tool call IDs const TOOL_CALL_ID_PATTERN = /^[a-zA-Z0-9]{9}$/; @@ -107719,6 +118104,8 @@ function _mistralContentChunkToMessageContentComplex(content) { + + function convertMessagesToMistralMessages(messages) { const getRole = (role) => { switch (role) { @@ -107953,19 +118340,32 @@ function _convertDeltaToMessageChunk(delta, usage) { } } function _convertToolToMistralTool(tools) { + if (!tools || !tools.length) { + return undefined; + } return tools.map((tool) => { + // If already a MistralAITool with a 'function' property, return as is if ("function" in tool) { - return tool; + return { + type: tool.type ?? "function", + function: tool.function, + }; } - const description = tool.description ?? `Tool: ${tool.name}`; - return { - type: "function", - function: { - name: tool.name, - description, - parameters: zodToJsonSchema_zodToJsonSchema(tool.schema), - }, - }; + // If it's a LangChain tool, convert to MistralAITool + if (types_isLangChainTool(tool)) { + const description = tool.description ?? `Tool: ${tool.name}`; + return { + type: "function", + function: { + name: tool.name, + description, + parameters: isInteropZodSchema(tool.schema) + ? json_schema_toJsonSchema(tool.schema) + : tool.schema, + }, + }; + } + throw new Error(`Unknown tool type passed to ChatMistral: ${JSON.stringify(tool, null, 2)}`); }); } /** @@ -107984,22 +118384,19 @@ function _convertToolToMistralTool(tools) { * ## [Runtime args](https://api.js.langchain.com/interfaces/_langchain_mistralai.ChatMistralAICallOptions.html) * * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. - * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below: + * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: * * ```typescript - * // When calling `.bind`, call options should be passed via the first argument - * const llmWithArgsBound = llm.bind({ - * stop: ["\n"], - * tools: [...], - * }); + * // When calling `.withConfig`, call options should be passed via the first argument + * const llmWithArgsBound = llm.bindTools([...]) // tools array + * .withConfig({ + * stop: ["\n"], // other call options + * }); * - * // When calling `.bindTools`, call options should be passed via the second argument - * const llmWithTools = llm.bindTools( - * [...], - * { - * tool_choice: "auto", - * } - * ); + * // You can also bind tools and call options like this + * const llmWithTools = llm.bindTools([...], { + * tool_choice: "auto", + * }); * ``` * * ## Examples @@ -108520,9 +118917,14 @@ class ChatMistralAI extends BaseChatModel { return params; } bindTools(tools, kwargs) { - return this.bind({ - tools: _convertToolToMistralTool(tools), - ...kwargs, + const mistralTools = _convertToolToMistralTool(tools); + return new RunnableBinding({ + bound: this, + kwargs: { + ...(kwargs ?? {}), + tools: mistralTools, + }, + config: {}, }); } async completionWithRetry(input, streaming) { @@ -108748,10 +119150,10 @@ class ChatMistralAI extends BaseChatModel { let llm; let outputParser; if (method === "jsonMode") { - llm = this.bind({ + llm = this.withConfig({ response_format: { type: "json_object" }, }); - if (chat_models_isZodSchema(schema)) { + if (isInteropZodSchema(schema)) { outputParser = StructuredOutputParser.fromZodSchema(schema); } else { @@ -108761,19 +119163,18 @@ class ChatMistralAI extends BaseChatModel { else { let functionName = name ?? "extract"; // Is function calling - if (chat_models_isZodSchema(schema)) { - const asJsonSchema = zodToJsonSchema_zodToJsonSchema(schema); - llm = this.bind({ - tools: [ - { - type: "function", - function: { - name: functionName, - description: asJsonSchema.description, - parameters: asJsonSchema, - }, + if (isInteropZodSchema(schema)) { + const asJsonSchema = json_schema_toJsonSchema(schema); + llm = this.bindTools([ + { + type: "function", + function: { + name: functionName, + description: asJsonSchema.description, + parameters: asJsonSchema, }, - ], + }, + ]).withConfig({ tool_choice: "any", }); outputParser = new JsonOutputKeyToolsParser({ @@ -108797,13 +119198,12 @@ class ChatMistralAI extends BaseChatModel { parameters: schema, }; } - llm = this.bind({ - tools: [ - { - type: "function", - function: openAIFunctionDefinition, - }, - ], + llm = this.bindTools([ + { + type: "function", + function: openAIFunctionDefinition, + }, + ]).withConfig({ tool_choice: "any", }); outputParser = new JsonOutputKeyToolsParser({ @@ -108833,12 +119233,6 @@ class ChatMistralAI extends BaseChatModel { ]); } } -function chat_models_isZodSchema( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -input) { - // Check for a characteristic method of Zod schemas - return typeof input?.parse === "function"; -} ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/embeddings.js @@ -111403,27 +121797,27 @@ var micromatch = __nccwpck_require__(8785); ;// CONCATENATED MODULE: ./utils/types.js -const aDiff = z.object({ - path: z.string(), - position: z.number(), - line: z.number(), - change: z.object({ - type: z.string(), - add: z.boolean(), - ln: z.number(), - content: z.string(), - relativePosition: z.number(), +const aDiff = objectType({ + path: stringType(), + position: numberType(), + line: numberType(), + change: objectType({ + type: stringType(), + add: booleanType(), + ln: numberType(), + content: stringType(), + relativePosition: numberType(), }), - previously: z.union([z.string(), z.null()]), - suggestions: z.union([z.string(), z.null()]), + previously: unionType([stringType(), nullType()]), + suggestions: unionType([stringType(), nullType()]), }); -const diffPayloadSchema = z.object({ - commentsToAdd: z.array(aDiff), +const diffPayloadSchema = objectType({ + commentsToAdd: arrayType(aDiff), }); const diffPayloadSchemaWithRequiredSuggestions = diffPayloadSchema.extend({ - commentsToAdd: z.array(aDiff.extend({ suggestions: z.string() })), + commentsToAdd: arrayType(aDiff.extend({ suggestions: stringType() })), }); @@ -111945,7 +122339,7 @@ async function getSuggestions({ ); } catch (err) { error(`Could not generate suggestions: ${err.message}`); - core.setFailed(`Could not generate suggestions: ${err.message}`); + lib_core.setFailed(`Could not generate suggestions: ${err.message}`); return null; } } @@ -112064,9 +122458,9 @@ function log({ withTimestamp = true }) { */ const getLogText = str => (withTimestamp ? `[${new Date().toISOString()}]: ${str}` : str); return { - info: message => core.info(getLogText(message)), - warning: message => core.warning(getLogText(message)), - error: error => core.error(getLogText(error)), + info: message => lib_core.info(getLogText(message)), + warning: message => lib_core.warning(getLogText(message)), + error: error => lib_core.error(getLogText(error)), }; } @@ -112093,14 +122487,14 @@ async function run() { try { info("Retrieving tokens and inputs..."); - const deleteExistingReviews = core.getInput("delete-existing-review-by-bot"); - const rules = core.getInput("rules"); - const token = core.getInput("repo-token"); - const modelName = core.getInput("ai-model-name"); - const modelToken = core.getInput("ai-model-api-key"); - const platform = core.getInput("platform"); - const filesToIgnore = core.getInput("filesToIgnore"); - const maxRetries = core.getInput("max-retries"); + const deleteExistingReviews = lib_core.getInput("delete-existing-review-by-bot"); + const rules = lib_core.getInput("rules"); + const token = lib_core.getInput("repo-token"); + const modelName = lib_core.getInput("ai-model-name"); + const modelToken = lib_core.getInput("ai-model-api-key"); + const platform = lib_core.getInput("platform"); + const filesToIgnore = lib_core.getInput("filesToIgnore"); + const maxRetries = lib_core.getInput("max-retries"); const octokit = github.getOctokit(token); info("Initializing AI model..."); @@ -112194,7 +122588,7 @@ async function run() { } } catch (err) { error(err); - core.setFailed(err.message); + lib_core.setFailed(err.message); } } diff --git a/package-lock.json b/package-lock.json index 058ffe4..0583212 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,26 +11,26 @@ "dependencies": { "@actions/core": "^1.11.1", "@actions/github": "^6.0.1", - "@anthropic-ai/sdk": "^0.50.4", - "@langchain/core": "^0.3.55", - "@langchain/mistralai": "^0.2.0", + "@anthropic-ai/sdk": "^0.54.0", + "@langchain/core": "^0.3.58", + "@langchain/mistralai": "^0.2.1", "is-ci": "^4.1.0", "micromatch": "^4.0.8", "openai": "^4.98.0", "parse-diff": "^0.11.1", - "zod": "^3.24.4", + "zod": "^3.25.64", "zod-to-json-schema": "^3.24.5" }, "devDependencies": { - "@eslint/js": "^9.26.0", + "@eslint/js": "^9.29.0", "@vercel/ncc": "^0.38.3", - "eslint": "^9.26.0", + "eslint": "^9.29.0", "eslint-config-google": "^0.14.0", "eslint-config-prettier": "^10.1.5", - "eslint-plugin-jsdoc": "^50.6.17", - "globals": "^16.1.0", + "eslint-plugin-jsdoc": "^51.0.1", + "globals": "^16.2.0", "husky": "^9.1.7", - "lint-staged": "^16.0.0", + "lint-staged": "^16.1.2", "npm-check-updates": "^18.0.1", "npm-run-all": "^4.1.5", "prettier": "^3.5.3" @@ -87,15 +87,12 @@ "license": "MIT" }, "node_modules/@anthropic-ai/sdk": { - "version": "0.50.4", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.50.4.tgz", - "integrity": "sha512-zZOWyIuznx2uqiRcCNuidkAsLC8IBHgS9lTwSVEB29sUCwEcqL95MWpWP1nccHSKfiZga+hbZaI0btR2zjuMmw==", + "version": "0.54.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.54.0.tgz", + "integrity": "sha512-xyoCtHJnt/qg5GG6IgK+UJEndz8h8ljzt/caKXmq3LfBF81nC/BW6E4x2rOWCZcvsLyVW+e8U5mtIr6UCE/kJw==", "license": "MIT", "bin": { "anthropic-ai-sdk": "bin/cli" - }, - "engines": { - "node": ">= 20" } }, "node_modules/@cfworker/json-schema": { @@ -105,13 +102,12 @@ "license": "MIT" }, "node_modules/@es-joy/jsdoccomment": { - "version": "0.50.1", - "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.50.1.tgz", - "integrity": "sha512-fas3qe1hw38JJgU/0m5sDpcrbZGysBeZcMwW5Ws9brYxY64MJyWLXRZCj18keTycT1LFTrFXdSNMS+GRVaU6Hw==", + "version": "0.50.2", + "resolved": "https://registry.npmjs.org/@es-joy/jsdoccomment/-/jsdoccomment-0.50.2.tgz", + "integrity": "sha512-YAdE/IJSpwbOTiaURNCKECdAwqrJuFiZhylmesBcIRawtYKnBR2wxPhoIewMg+Yu+QuYvHfJNReWpoxGBKOChA==", "dev": true, "license": "MIT", "dependencies": { - "@types/eslint": "^9.6.1", "@types/estree": "^1.0.6", "@typescript-eslint/types": "^8.11.0", "comment-parser": "1.4.1", @@ -162,9 +158,9 @@ } }, "node_modules/@eslint/config-array": { - "version": "0.20.0", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.20.0.tgz", - "integrity": "sha512-fxlS1kkIjx8+vy2SjuCB94q3htSNrufYTXubwiBFeaQHbH6Ipi43gFJq2zCMt6PHhImH3Xmr0NksKDvchWlpQQ==", + "version": "0.20.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.20.1.tgz", + "integrity": "sha512-OL0RJzC/CBzli0DrrR31qzj6d6i6Mm3HByuhflhl4LOBiWxN+3i6/t/ZQQNii4tjksXi8r2CRW1wMpWA2ULUEw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -187,9 +183,9 @@ } }, "node_modules/@eslint/core": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.13.0.tgz", - "integrity": "sha512-yfkgDw1KR66rkT5A8ci4irzDysN7FRpq3ttJolR88OqQikAWqwA8j5VZyas+vjyBNFIJ7MfybJ9plMILI2UrCw==", + "version": "0.14.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.14.0.tgz", + "integrity": "sha512-qIbV0/JZr7iSDjqAc60IqbLdsj9GDt16xQtWD+B78d/HAlvysGdZZ6rpJHGAc2T0FQx1X6thsSPdnoiGKdNtdg==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -237,13 +233,16 @@ } }, "node_modules/@eslint/js": { - "version": "9.26.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.26.0.tgz", - "integrity": "sha512-I9XlJawFdSMvWjDt6wksMCrgns5ggLNfFwFvnShsleWruvXM514Qxk8V246efTw+eo9JABvVz+u3q2RiAowKxQ==", + "version": "9.29.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.29.0.tgz", + "integrity": "sha512-3PIF4cBw/y+1u2EazflInpV+lYsSG0aByVIQzAgb1m1MhHFSbqTyNqtBKHgWf/9Ykud+DhILS9EGkmekVhbKoQ==", "dev": true, "license": "MIT", "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" } }, "node_modules/@eslint/object-schema": { @@ -257,19 +256,32 @@ } }, "node_modules/@eslint/plugin-kit": { - "version": "0.2.8", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.2.8.tgz", - "integrity": "sha512-ZAoA40rNMPwSm+AeHpCq8STiNAwzWLJuP8Xv4CHIc9wv/PSuExjMrmjfYNj682vW0OOiZ1HKxzvjQr9XZIisQA==", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.3.2.tgz", + "integrity": "sha512-4SaFZCNfJqvk/kenHpI8xvN42DMaoycy4PzKc5otHxRswww1kAt82OlBuwRVLofCACCTZEcla2Ydxv8scMXaTg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@eslint/core": "^0.13.0", + "@eslint/core": "^0.15.0", "levn": "^0.4.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@eslint/plugin-kit/node_modules/@eslint/core": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.15.0.tgz", + "integrity": "sha512-b7ePw78tEWWkpgZCDYkbqDOP8dmM6qe+AOC6iuJqlq1R/0ahMAeH3qynpnqKFGkMltrp44ohV4ubGyvLX28tzw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@fastify/busboy": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", @@ -346,9 +358,9 @@ } }, "node_modules/@langchain/core": { - "version": "0.3.55", - "resolved": "https://registry.npmjs.org/@langchain/core/-/core-0.3.55.tgz", - "integrity": "sha512-SojY2ugpT6t9eYfFB9Ysvyhhyh+KJTGXs50hdHUE9tAEQWp3WAwoxe4djwJnOZ6fSpWYdpFt2UT2ksHVDy2vXA==", + "version": "0.3.58", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-0.3.58.tgz", + "integrity": "sha512-HLkOtVofgBHefaUae/+2fLNkpMLzEjHSavTmUF0YC7bDa5NPIZGlP80CGrSFXAeJ+WCPd8rIK8K/p6AW94inUQ==", "license": "MIT", "dependencies": { "@cfworker/json-schema": "^4.0.2", @@ -356,12 +368,12 @@ "camelcase": "6", "decamelize": "1.2.0", "js-tiktoken": "^1.0.12", - "langsmith": "^0.3.16", + "langsmith": "^0.3.29", "mustache": "^4.2.0", "p-queue": "^6.6.2", "p-retry": "4", "uuid": "^10.0.0", - "zod": "^3.22.4", + "zod": "^3.25.32", "zod-to-json-schema": "^3.22.3" }, "engines": { @@ -381,21 +393,19 @@ } }, "node_modules/@langchain/mistralai": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@langchain/mistralai/-/mistralai-0.2.0.tgz", - "integrity": "sha512-VdfbKZopAuSXf/vlXbriGWLK3c7j5s47DoB3S31xpprY2BMSKZZiX9vE9TsgxMfAPuIDPIYcfgU7p1upvTYt8g==", + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/@langchain/mistralai/-/mistralai-0.2.1.tgz", + "integrity": "sha512-s91BlNcuxaaZGnVukyl81nwGrWpeE0EYiAdEFoBmZwlT4yLpx+QpPhRsGKrTg/Vm7Nscy6Wd8Xy2PJ93wftMdw==", "license": "MIT", "dependencies": { "@mistralai/mistralai": "^1.3.1", - "uuid": "^10.0.0", - "zod": "^3.23.8", - "zod-to-json-schema": "^3.22.4" + "uuid": "^10.0.0" }, "engines": { "node": ">=18" }, "peerDependencies": { - "@langchain/core": ">=0.3.7 <0.4.0" + "@langchain/core": ">=0.3.58 <0.4.0" } }, "node_modules/@mistralai/mistralai": { @@ -408,28 +418,6 @@ "zod": ">= 3" } }, - "node_modules/@modelcontextprotocol/sdk": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.11.3.tgz", - "integrity": "sha512-rmOWVRUbUJD7iSvJugjUbFZshTAuJ48MXoZ80Osx1GM0K/H1w7rSEvmw8m6vdWxNASgtaHIhAgre4H/E9GJiYQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "content-type": "^1.0.5", - "cors": "^2.8.5", - "cross-spawn": "^7.0.5", - "eventsource": "^3.0.2", - "express": "^5.0.1", - "express-rate-limit": "^7.5.0", - "pkce-challenge": "^5.0.0", - "raw-body": "^3.0.0", - "zod": "^3.23.8", - "zod-to-json-schema": "^3.24.1" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/@octokit/auth-token": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-4.0.0.tgz", @@ -588,17 +576,6 @@ "@octokit/openapi-types": "^22.2.0" } }, - "node_modules/@types/eslint": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", - "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "*", - "@types/json-schema": "*" - } - }, "node_modules/@types/estree": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", @@ -645,9 +622,9 @@ "license": "MIT" }, "node_modules/@typescript-eslint/types": { - "version": "8.32.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.32.1.tgz", - "integrity": "sha512-YmybwXUJcgGqgAp6bEsgpPXEg6dcCyPyCSr0CAAueacR/CCBi25G3V8gGQ2kRzQRBNol7VQknxMs9HvVa9Rvfg==", + "version": "8.34.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.34.0.tgz", + "integrity": "sha512-9V24k/paICYPniajHfJ4cuAWETnt7Ssy+R0Rbcqo5sSFr3QEZ/8TSoUi9XeXVBGXCaLtwTOKSLGcInCAvyZeMA==", "dev": true, "license": "MIT", "engines": { @@ -680,24 +657,10 @@ "node": ">=6.5" } }, - "node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/acorn": { - "version": "8.14.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.0.tgz", - "integrity": "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA==", + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", "bin": { @@ -791,13 +754,13 @@ } }, "node_modules/are-docs-informative": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/are-docs-informative/-/are-docs-informative-0.0.2.tgz", - "integrity": "sha512-ixiS0nLNNG5jNQzgZJNoUpBKdo9yTYZMGJ+QgT2jmjR7G7+QHRCc4v6LQ3NgE7EBJq+o0ams3waJwkrlBom8Ig==", + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/are-docs-informative/-/are-docs-informative-0.1.1.tgz", + "integrity": "sha512-sqRsNQBwbKLRX0jV5Cu5uzmtflf892n4Vukz7T659ebL4pz3mpOqCMU7lxMoBTFwnp10E3YB5ZcyHM41W5bcDA==", "dev": true, "license": "MIT", "engines": { - "node": ">=14" + "node": ">=18" } }, "node_modules/argparse": { @@ -902,27 +865,6 @@ "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==", "license": "Apache-2.0" }, - "node_modules/body-parser": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", - "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "bytes": "^3.1.2", - "content-type": "^1.0.5", - "debug": "^4.4.0", - "http-errors": "^2.0.0", - "iconv-lite": "^0.6.3", - "on-finished": "^2.4.1", - "qs": "^6.14.0", - "raw-body": "^3.0.0", - "type-is": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -946,16 +888,6 @@ "node": ">=8" } }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/call-bind": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.7.tgz", @@ -1130,13 +1062,13 @@ } }, "node_modules/commander": { - "version": "13.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", - "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.0.tgz", + "integrity": "sha512-2uM9rYjPvyq39NwLRqaiLtWHyDC1FvryJDa2ATTVims5YAS4PupsEQsDvP14FqhFr0P49CYDugi59xaxJlTXRA==", "dev": true, "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/comment-parser": { @@ -1157,71 +1089,14 @@ "license": "MIT" }, "node_modules/console-table-printer": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.12.1.tgz", - "integrity": "sha512-wKGOQRRvdnd89pCeH96e2Fn4wkbenSP6LMHfjfyNLMbGuHEFbMqQNuxXqd0oXG9caIOQ1FTvc5Uijp9/4jujnQ==", + "version": "2.14.3", + "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.14.3.tgz", + "integrity": "sha512-X5OCFnjYlXzRuC8ac5hPA2QflRjJvNKJocMhlnqK/Ap7q3DHXr0NJ0TGzwmEKOiOdJrjsSwEd0m+a32JAYPrKQ==", "license": "MIT", "dependencies": { "simple-wcswidth": "^1.0.1" } }, - "node_modules/content-disposition": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.0.tgz", - "integrity": "sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==", - "dev": true, - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", - "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.6.0" - } - }, - "node_modules/cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -1292,9 +1167,9 @@ } }, "node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1370,16 +1245,6 @@ "node": ">=0.4.0" } }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/deprecation": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", @@ -1400,13 +1265,6 @@ "node": ">= 0.4" } }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "dev": true, - "license": "MIT" - }, "node_modules/emoji-regex": { "version": "10.4.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.4.0.tgz", @@ -1414,16 +1272,6 @@ "dev": true, "license": "MIT" }, - "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/environment": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", @@ -1571,13 +1419,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "dev": true, - "license": "MIT" - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -1592,24 +1433,23 @@ } }, "node_modules/eslint": { - "version": "9.26.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.26.0.tgz", - "integrity": "sha512-Hx0MOjPh6uK9oq9nVsATZKE/Wlbai7KFjfCuw9UHaguDW3x+HF0O5nIi3ud39TWgrTjTO5nHxmL3R1eANinWHQ==", + "version": "9.29.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.29.0.tgz", + "integrity": "sha512-GsGizj2Y1rCWDu6XoEekL3RLilp0voSePurjZIkxL3wlm5o5EC9VpgaP7lrCvjnkuLvzFBQWB3vWB3K5KQTveQ==", "dev": true, "license": "MIT", "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", - "@eslint/config-array": "^0.20.0", + "@eslint/config-array": "^0.20.1", "@eslint/config-helpers": "^0.2.1", - "@eslint/core": "^0.13.0", + "@eslint/core": "^0.14.0", "@eslint/eslintrc": "^3.3.1", - "@eslint/js": "9.26.0", - "@eslint/plugin-kit": "^0.2.8", + "@eslint/js": "9.29.0", + "@eslint/plugin-kit": "^0.3.1", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", - "@modelcontextprotocol/sdk": "^1.8.0", "@types/estree": "^1.0.6", "@types/json-schema": "^7.0.15", "ajv": "^6.12.4", @@ -1617,9 +1457,9 @@ "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^8.3.0", - "eslint-visitor-keys": "^4.2.0", - "espree": "^10.3.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", @@ -1633,8 +1473,7 @@ "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "zod": "^3.24.2" + "optionator": "^0.9.3" }, "bin": { "eslint": "bin/eslint.js" @@ -1684,34 +1523,34 @@ } }, "node_modules/eslint-plugin-jsdoc": { - "version": "50.6.17", - "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-50.6.17.tgz", - "integrity": "sha512-hq+VQylhd12l8qjexyriDsejZhqiP33WgMTy2AmaGZ9+MrMWVqPECsM87GPxgHfQn0zw+YTuhqjUfk1f+q67aQ==", + "version": "51.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-51.0.1.tgz", + "integrity": "sha512-nnH6O8uk0Wp5EvHlVEPESKdGWTlu5g1tfBUZmL/jMZLBpUtttxxW+9hPzTMCYmYsQ3HwDsJdHJAiaDRKsP6iUg==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "@es-joy/jsdoccomment": "~0.50.1", - "are-docs-informative": "^0.0.2", + "@es-joy/jsdoccomment": "~0.50.2", + "are-docs-informative": "^0.1.1", "comment-parser": "1.4.1", - "debug": "^4.3.6", + "debug": "^4.4.1", "escape-string-regexp": "^4.0.0", - "espree": "^10.1.0", + "espree": "^10.3.0", "esquery": "^1.6.0", "parse-imports-exports": "^0.2.4", - "semver": "^7.6.3", + "semver": "^7.7.2", "spdx-expression-parse": "^4.0.0" }, "engines": { - "node": ">=18" + "node": ">=22" }, "peerDependencies": { "eslint": "^7.0.0 || ^8.0.0 || ^9.0.0" } }, "node_modules/eslint-scope": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.3.0.tgz", - "integrity": "sha512-pUNxi75F8MJ/GdeKtVLSbYg4ZI34J6C0C7sbL4YOp2exGwen7ZsuBqKzUhXd0qMQ362yET3z+uPwKeg/0C2XCQ==", + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -1726,9 +1565,9 @@ } }, "node_modules/eslint-visitor-keys": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz", - "integrity": "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", "dev": true, "license": "Apache-2.0", "engines": { @@ -1739,15 +1578,15 @@ } }, "node_modules/espree": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-10.3.0.tgz", - "integrity": "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg==", + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", "dev": true, "license": "BSD-2-Clause", "dependencies": { - "acorn": "^8.14.0", + "acorn": "^8.15.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^4.2.0" + "eslint-visitor-keys": "^4.2.1" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -1802,16 +1641,6 @@ "node": ">=0.10.0" } }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", @@ -1828,88 +1657,6 @@ "dev": true, "license": "MIT" }, - "node_modules/eventsource": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", - "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eventsource-parser": "^3.0.1" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/eventsource-parser": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.2.tgz", - "integrity": "sha512-6RxOBZ/cYgd8usLwsEl+EC09Au/9BcmCKYF2/xbml6DNczf7nv0MQb+7BA2F+li6//I+28VNlQR37XfQtcAJuA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/express": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", - "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", - "dev": true, - "license": "MIT", - "dependencies": { - "accepts": "^2.0.0", - "body-parser": "^2.2.0", - "content-disposition": "^1.0.0", - "content-type": "^1.0.5", - "cookie": "^0.7.1", - "cookie-signature": "^1.2.1", - "debug": "^4.4.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "finalhandler": "^2.1.0", - "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "merge-descriptors": "^2.0.0", - "mime-types": "^3.0.0", - "on-finished": "^2.4.1", - "once": "^1.4.0", - "parseurl": "^1.3.3", - "proxy-addr": "^2.0.7", - "qs": "^6.14.0", - "range-parser": "^1.2.1", - "router": "^2.2.0", - "send": "^1.1.0", - "serve-static": "^2.2.0", - "statuses": "^2.0.1", - "type-is": "^2.0.1", - "vary": "^1.1.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/express-rate-limit": { - "version": "7.5.0", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.0.tgz", - "integrity": "sha512-eB5zbQh5h+VenMPM3fh+nw1YExi5nMr6HUCR62ELSP11huvxm/Uir1H1QEyTkk5QX6A58pX6NmaTMceKZ0Eodg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": "^4.11 || 5 || ^5.0.0-beta.1" - } - }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -1956,24 +1703,6 @@ "node": ">=8" } }, - "node_modules/finalhandler": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", - "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "on-finished": "^2.4.1", - "parseurl": "^1.3.3", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -2077,26 +1806,6 @@ "node": ">= 12.20" } }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -2217,9 +1926,9 @@ } }, "node_modules/globals": { - "version": "16.1.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-16.1.0.tgz", - "integrity": "sha512-aibexHNbb/jiUSObBgpHLj+sIuUmJnYcgXBlrfsiDZ9rt4aF2TFRbyLgZ2iFQuVZ1K5Mx3FVkbKRSgKrbK3K2g==", + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.2.0.tgz", + "integrity": "sha512-O+7l9tPdHCU320IigZZPj5zmRCFG9xHmx9cU8FqU2Rp+JN714seHV+2S9+JslCpY4gJwU2vOGox0wzgae/MCEg==", "dev": true, "license": "MIT", "engines": { @@ -2356,23 +2065,6 @@ "dev": true, "license": "ISC" }, - "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/humanize-ms": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", @@ -2398,19 +2090,6 @@ "url": "https://github.com/sponsors/typicode" } }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -2448,13 +2127,6 @@ "node": ">=0.8.19" } }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC" - }, "node_modules/internal-slot": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz", @@ -2470,16 +2142,6 @@ "node": ">= 0.4" } }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, "node_modules/is-array-buffer": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz", @@ -2687,13 +2349,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "dev": true, - "license": "MIT" - }, "node_modules/is-regex": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz", @@ -2873,9 +2528,9 @@ } }, "node_modules/langsmith": { - "version": "0.3.28", - "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.28.tgz", - "integrity": "sha512-Vq8n0zJ9MhDMhwkOhmOEb/rl/8jpm0LnAF4dE5TEXMdLmhJ784gcrWOghnFh7Qs5B4DY2Bdz3OKxIevkGKn5xg==", + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.31.tgz", + "integrity": "sha512-9lwuLZuN3tXFYQ6eMg0rmbBw7oxQo4bu1NYeylbjz27bOdG1XB9XNoxaiIArkK4ciLdOIOhPMBXP4bkvZOgHRw==", "license": "MIT", "dependencies": { "@types/uuid": "^10.0.0", @@ -2923,28 +2578,28 @@ } }, "node_modules/lint-staged": { - "version": "16.0.0", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.0.0.tgz", - "integrity": "sha512-sUCprePs6/rbx4vKC60Hez6X10HPkpDJaGcy3D1NdwR7g1RcNkWL8q9mJMreOqmHBTs+1sNFp+wOiX9fr+hoOQ==", + "version": "16.1.2", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-16.1.2.tgz", + "integrity": "sha512-sQKw2Si2g9KUZNY3XNvRuDq4UJqpHwF0/FQzZR2M7I5MvtpWvibikCjUVJzZdGE0ByurEl3KQNvsGetd1ty1/Q==", "dev": true, "license": "MIT", "dependencies": { "chalk": "^5.4.1", - "commander": "^13.1.0", - "debug": "^4.4.0", + "commander": "^14.0.0", + "debug": "^4.4.1", "lilconfig": "^3.1.3", "listr2": "^8.3.3", "micromatch": "^4.0.8", - "nano-spawn": "^1.0.0", + "nano-spawn": "^1.0.2", "pidtree": "^0.6.0", "string-argv": "^0.3.2", - "yaml": "^2.7.1" + "yaml": "^2.8.0" }, "bin": { "lint-staged": "bin/lint-staged.js" }, "engines": { - "node": ">=20.18" + "node": ">=20.17" }, "funding": { "url": "https://opencollective.com/lint-staged" @@ -3095,16 +2750,6 @@ "node": ">= 0.4" } }, - "node_modules/media-typer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", - "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/memorystream": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", @@ -3114,19 +2759,6 @@ "node": ">= 0.10.0" } }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -3140,29 +2772,6 @@ "node": ">=8.6" } }, - "node_modules/mime-db": { - "version": "1.54.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", - "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.1.tgz", - "integrity": "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/mimic-function": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", @@ -3205,13 +2814,13 @@ } }, "node_modules/nano-spawn": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/nano-spawn/-/nano-spawn-1.0.1.tgz", - "integrity": "sha512-BfcvzBlUTxSDWfT+oH7vd6CbUV+rThLLHCIym/QO6GGLBsyVXleZs00fto2i2jzC/wPiBYk5jyOmpXWg4YopiA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/nano-spawn/-/nano-spawn-1.0.2.tgz", + "integrity": "sha512-21t+ozMQDAL/UGgQVBbZ/xXvNO10++ZPuTmKRO8k9V3AClVRht49ahtDjfY8l1q6nSHOrE5ASfthzH3ol6R/hg==", "dev": true, "license": "MIT", "engines": { - "node": ">=20.18" + "node": ">=20.17" }, "funding": { "url": "https://github.com/sindresorhus/nano-spawn?sponsor=1" @@ -3224,16 +2833,6 @@ "dev": true, "license": "MIT" }, - "node_modules/negotiator": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", - "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/nice-try": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", @@ -3509,16 +3108,6 @@ "which": "bin/which" } }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -3561,19 +3150,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "dev": true, - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -3785,16 +3361,6 @@ "dev": true, "license": "MIT" }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3822,16 +3388,6 @@ "dev": true, "license": "MIT" }, - "node_modules/path-to-regexp": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.2.0.tgz", - "integrity": "sha512-TdrF7fW9Rphjq4RjrW0Kp2AW0Ahwu9sRGTkS6bvDi0SCwZlEZYmcfDbEsTz8RVk0EHIS/Vd1bv3JhG+1xZuAyQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=16" - } - }, "node_modules/path-type": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", @@ -3880,16 +3436,6 @@ "node": ">=4" } }, - "node_modules/pkce-challenge": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.0.tgz", - "integrity": "sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=16.20.0" - } - }, "node_modules/possible-typed-array-names": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz", @@ -3926,20 +3472,6 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, - "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -3950,48 +3482,6 @@ "node": ">=6" } }, - "node_modules/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/raw-body": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.0.tgz", - "integrity": "sha512-RmkhL8CAyCRPXCE28MMH0z2PNWQBNk2Q09ZdxM9IOOXwxwZbN+qbWaatPkdkWIKL2ZVDImrN/pK5HTRz2PcS4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.6.3", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/react": { "version": "19.0.0", "resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz", @@ -4110,23 +3600,6 @@ "dev": true, "license": "MIT" }, - "node_modules/router": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", - "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "depd": "^2.0.0", - "is-promise": "^4.0.0", - "parseurl": "^1.3.3", - "path-to-regexp": "^8.0.0" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/safe-array-concat": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz", @@ -4146,27 +3619,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/safe-regex-test": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz", @@ -4185,13 +3637,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" - }, "node_modules/scheduler": { "version": "0.25.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.25.0.tgz", @@ -4200,9 +3645,9 @@ "peer": true }, "node_modules/semver": { - "version": "7.6.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", - "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", + "version": "7.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -4211,45 +3656,6 @@ "node": ">=10" } }, - "node_modules/send": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", - "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.3.5", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "mime-types": "^3.0.1", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/serve-static": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", - "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.2.0" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/set-function-length": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", @@ -4284,13 +3690,6 @@ "node": ">= 0.4" } }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "dev": true, - "license": "ISC" - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -4414,9 +3813,9 @@ } }, "node_modules/simple-wcswidth": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.0.1.tgz", - "integrity": "sha512-xMO/8eNREtaROt7tJvWJqHBDTMFN4eiQ5I4JRMuilwfnFcV5W9u7RUkueNkdw0jPqGMX36iCywelS5yilTuOxg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.1.tgz", + "integrity": "sha512-R3q3/eoeNBp24CNTASEUrffXi0j9TwPIEvSStlvSrsFimM17sV5EHcMOc86j3K+UWZyLYvH0hRmYGCpCoaJ4vw==", "license": "MIT" }, "node_modules/slice-ansi": { @@ -4496,16 +3895,6 @@ "dev": true, "license": "CC0-1.0" }, - "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/string-argv": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", @@ -4681,16 +4070,6 @@ "node": ">=8.0" } }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, "node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", @@ -4719,21 +4098,6 @@ "node": ">= 0.8.0" } }, - "node_modules/type-is": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", - "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", - "dev": true, - "license": "MIT", - "dependencies": { - "content-type": "^1.0.5", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/typed-array-buffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz", @@ -4851,16 +4215,6 @@ "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==", "license": "ISC" }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", @@ -4906,16 +4260,6 @@ "spdx-license-ids": "^3.0.0" } }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "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", @@ -5068,9 +4412,9 @@ } }, "node_modules/zod": { - "version": "3.24.4", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.24.4.tgz", - "integrity": "sha512-OdqJE9UDRPwWsrHjLN2F8bPxvwJBK22EHLWtanu0LSYr5YqzsaaW3RMgmjwr8Rypg5k+meEJdSPXJZXE/yqOMg==", + "version": "3.25.64", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.64.tgz", + "integrity": "sha512-hbP9FpSZf7pkS7hRVUrOjhwKJNyampPgtXKc3AN6DsWtoHsg2Sb4SQaS4Tcay380zSwd2VPo9G9180emBACp5g==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/package.json b/package.json index 6960ce1..e94d43a 100644 --- a/package.json +++ b/package.json @@ -25,26 +25,26 @@ "dependencies": { "@actions/core": "^1.11.1", "@actions/github": "^6.0.1", - "@anthropic-ai/sdk": "^0.50.4", - "@langchain/core": "^0.3.55", - "@langchain/mistralai": "^0.2.0", + "@anthropic-ai/sdk": "^0.54.0", + "@langchain/core": "^0.3.58", + "@langchain/mistralai": "^0.2.1", "is-ci": "^4.1.0", "micromatch": "^4.0.8", "openai": "^4.98.0", "parse-diff": "^0.11.1", - "zod": "^3.24.4", + "zod": "^3.25.64", "zod-to-json-schema": "^3.24.5" }, "devDependencies": { - "@eslint/js": "^9.26.0", + "@eslint/js": "^9.29.0", "@vercel/ncc": "^0.38.3", - "eslint": "^9.26.0", + "eslint": "^9.29.0", "eslint-config-google": "^0.14.0", "eslint-config-prettier": "^10.1.5", - "eslint-plugin-jsdoc": "^50.6.17", - "globals": "^16.1.0", + "eslint-plugin-jsdoc": "^51.0.1", + "globals": "^16.2.0", "husky": "^9.1.7", - "lint-staged": "^16.0.0", + "lint-staged": "^16.1.2", "npm-check-updates": "^18.0.1", "npm-run-all": "^4.1.5", "prettier": "^3.5.3" From d005f9f7c964395fcd9e7c7e75026ee588960991 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 21:29:57 +0530 Subject: [PATCH 08/14] chore: upgrade deps --- dist/index.js | 53195 +++++++++++++++++++------------------------- dist/licenses.txt | 1466 +- package-lock.json | 252 +- package.json | 2 +- 4 files changed, 24978 insertions(+), 29937 deletions(-) diff --git a/dist/index.js b/dist/index.js index 251e29b..a8e9683 100644 --- a/dist/index.js +++ b/dist/index.js @@ -24012,642 +24012,6 @@ var request = withDefaults(import_endpoint.endpoint, { 0 && (0); -/***/ }), - -/***/ 7413: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * @author Toru Nagashima - * See LICENSE file in root directory for full license. - */ - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var eventTargetShim = __nccwpck_require__(6577); - -/** - * The signal class. - * @see https://dom.spec.whatwg.org/#abortsignal - */ -class AbortSignal extends eventTargetShim.EventTarget { - /** - * AbortSignal cannot be constructed directly. - */ - constructor() { - super(); - throw new TypeError("AbortSignal cannot be constructed directly"); - } - /** - * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. - */ - get aborted() { - const aborted = abortedFlags.get(this); - if (typeof aborted !== "boolean") { - throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); - } - return aborted; - } -} -eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); -/** - * Create an AbortSignal object. - */ -function createAbortSignal() { - const signal = Object.create(AbortSignal.prototype); - eventTargetShim.EventTarget.call(signal); - abortedFlags.set(signal, false); - return signal; -} -/** - * Abort a given signal. - */ -function abortSignal(signal) { - if (abortedFlags.get(signal) !== false) { - return; - } - abortedFlags.set(signal, true); - signal.dispatchEvent({ type: "abort" }); -} -/** - * Aborted flag for each instances. - */ -const abortedFlags = new WeakMap(); -// Properties should be enumerable. -Object.defineProperties(AbortSignal.prototype, { - aborted: { enumerable: true }, -}); -// `toString()` should return `"[object AbortSignal]"` -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortSignal", - }); -} - -/** - * The AbortController. - * @see https://dom.spec.whatwg.org/#abortcontroller - */ -class AbortController { - /** - * Initialize this controller. - */ - constructor() { - signals.set(this, createAbortSignal()); - } - /** - * Returns the `AbortSignal` object associated with this object. - */ - get signal() { - return getSignal(this); - } - /** - * Abort and signal to any observers that the associated activity is to be aborted. - */ - abort() { - abortSignal(getSignal(this)); - } -} -/** - * Associated signals. - */ -const signals = new WeakMap(); -/** - * Get the associated signal of a given controller. - */ -function getSignal(controller) { - const signal = signals.get(controller); - if (signal == null) { - throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); - } - return signal; -} -// Properties should be enumerable. -Object.defineProperties(AbortController.prototype, { - signal: { enumerable: true }, - abort: { enumerable: true }, -}); -if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { - Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { - configurable: true, - value: "AbortController", - }); -} - -exports.AbortController = AbortController; -exports.AbortSignal = AbortSignal; -exports["default"] = AbortController; - -module.exports = AbortController -module.exports.AbortController = module.exports["default"] = AbortController -module.exports.AbortSignal = AbortSignal -//# sourceMappingURL=abort-controller.js.map - - -/***/ }), - -/***/ 3873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const HttpAgent = __nccwpck_require__(2532); -module.exports = HttpAgent; -module.exports.HttpAgent = HttpAgent; -module.exports.HttpsAgent = __nccwpck_require__(414); -module.exports.constants = __nccwpck_require__(6160); - - -/***/ }), - -/***/ 2532: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const OriginalAgent = (__nccwpck_require__(8611).Agent); -const ms = __nccwpck_require__(3724); -const debug = (__nccwpck_require__(9023).debuglog)('agentkeepalive'); -const { - INIT_SOCKET, - CURRENT_ID, - CREATE_ID, - SOCKET_CREATED_TIME, - SOCKET_NAME, - SOCKET_REQUEST_COUNT, - SOCKET_REQUEST_FINISHED_COUNT, -} = __nccwpck_require__(6160); - -// OriginalAgent come from -// - https://github.com/nodejs/node/blob/v8.12.0/lib/_http_agent.js -// - https://github.com/nodejs/node/blob/v10.12.0/lib/_http_agent.js - -// node <= 10 -let defaultTimeoutListenerCount = 1; -const majorVersion = parseInt(process.version.split('.', 1)[0].substring(1)); -if (majorVersion >= 11 && majorVersion <= 12) { - defaultTimeoutListenerCount = 2; -} else if (majorVersion >= 13) { - defaultTimeoutListenerCount = 3; -} - -function deprecate(message) { - console.log('[agentkeepalive:deprecated] %s', message); -} - -class Agent extends OriginalAgent { - constructor(options) { - options = options || {}; - options.keepAlive = options.keepAlive !== false; - // default is keep-alive and 4s free socket timeout - // see https://medium.com/ssense-tech/reduce-networking-errors-in-nodejs-23b4eb9f2d83 - if (options.freeSocketTimeout === undefined) { - options.freeSocketTimeout = 4000; - } - // Legacy API: keepAliveTimeout should be rename to `freeSocketTimeout` - if (options.keepAliveTimeout) { - deprecate('options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead'); - options.freeSocketTimeout = options.keepAliveTimeout; - delete options.keepAliveTimeout; - } - // Legacy API: freeSocketKeepAliveTimeout should be rename to `freeSocketTimeout` - if (options.freeSocketKeepAliveTimeout) { - deprecate('options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead'); - options.freeSocketTimeout = options.freeSocketKeepAliveTimeout; - delete options.freeSocketKeepAliveTimeout; - } - - // Sets the socket to timeout after timeout milliseconds of inactivity on the socket. - // By default is double free socket timeout. - if (options.timeout === undefined) { - // make sure socket default inactivity timeout >= 8s - options.timeout = Math.max(options.freeSocketTimeout * 2, 8000); - } - - // support humanize format - options.timeout = ms(options.timeout); - options.freeSocketTimeout = ms(options.freeSocketTimeout); - options.socketActiveTTL = options.socketActiveTTL ? ms(options.socketActiveTTL) : 0; - - super(options); - - this[CURRENT_ID] = 0; - - // create socket success counter - this.createSocketCount = 0; - this.createSocketCountLastCheck = 0; - - this.createSocketErrorCount = 0; - this.createSocketErrorCountLastCheck = 0; - - this.closeSocketCount = 0; - this.closeSocketCountLastCheck = 0; - - // socket error event count - this.errorSocketCount = 0; - this.errorSocketCountLastCheck = 0; - - // request finished counter - this.requestCount = 0; - this.requestCountLastCheck = 0; - - // including free socket timeout counter - this.timeoutSocketCount = 0; - this.timeoutSocketCountLastCheck = 0; - - this.on('free', socket => { - // https://github.com/nodejs/node/pull/32000 - // Node.js native agent will check socket timeout eqs agent.options.timeout. - // Use the ttl or freeSocketTimeout to overwrite. - const timeout = this.calcSocketTimeout(socket); - if (timeout > 0 && socket.timeout !== timeout) { - socket.setTimeout(timeout); - } - }); - } - - get freeSocketKeepAliveTimeout() { - deprecate('agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead'); - return this.options.freeSocketTimeout; - } - - get timeout() { - deprecate('agent.timeout is deprecated, please use agent.options.timeout instead'); - return this.options.timeout; - } - - get socketActiveTTL() { - deprecate('agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead'); - return this.options.socketActiveTTL; - } - - calcSocketTimeout(socket) { - /** - * return <= 0: should free socket - * return > 0: should update socket timeout - * return undefined: not find custom timeout - */ - let freeSocketTimeout = this.options.freeSocketTimeout; - const socketActiveTTL = this.options.socketActiveTTL; - if (socketActiveTTL) { - // check socketActiveTTL - const aliveTime = Date.now() - socket[SOCKET_CREATED_TIME]; - const diff = socketActiveTTL - aliveTime; - if (diff <= 0) { - return diff; - } - if (freeSocketTimeout && diff < freeSocketTimeout) { - freeSocketTimeout = diff; - } - } - // set freeSocketTimeout - if (freeSocketTimeout) { - // set free keepalive timer - // try to use socket custom freeSocketTimeout first, support headers['keep-alive'] - // https://github.com/node-modules/urllib/blob/b76053020923f4d99a1c93cf2e16e0c5ba10bacf/lib/urllib.js#L498 - const customFreeSocketTimeout = socket.freeSocketTimeout || socket.freeSocketKeepAliveTimeout; - return customFreeSocketTimeout || freeSocketTimeout; - } - } - - keepSocketAlive(socket) { - const result = super.keepSocketAlive(socket); - // should not keepAlive, do nothing - if (!result) return result; - - const customTimeout = this.calcSocketTimeout(socket); - if (typeof customTimeout === 'undefined') { - return true; - } - if (customTimeout <= 0) { - debug('%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], customTimeout); - return false; - } - if (socket.timeout !== customTimeout) { - socket.setTimeout(customTimeout); - } - return true; - } - - // only call on addRequest - reuseSocket(...args) { - // reuseSocket(socket, req) - super.reuseSocket(...args); - const socket = args[0]; - const req = args[1]; - req.reusedSocket = true; - const agentTimeout = this.options.timeout; - if (getSocketTimeout(socket) !== agentTimeout) { - // reset timeout before use - socket.setTimeout(agentTimeout); - debug('%s reset timeout to %sms', socket[SOCKET_NAME], agentTimeout); - } - socket[SOCKET_REQUEST_COUNT]++; - debug('%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], - getSocketTimeout(socket)); - } - - [CREATE_ID]() { - const id = this[CURRENT_ID]++; - if (this[CURRENT_ID] === Number.MAX_SAFE_INTEGER) this[CURRENT_ID] = 0; - return id; - } - - [INIT_SOCKET](socket, options) { - // bugfix here. - // https on node 8, 10 won't set agent.options.timeout by default - // TODO: need to fix on node itself - if (options.timeout) { - const timeout = getSocketTimeout(socket); - if (!timeout) { - socket.setTimeout(options.timeout); - } - } - - if (this.options.keepAlive) { - // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/ - // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html - socket.setNoDelay(true); - } - this.createSocketCount++; - if (this.options.socketActiveTTL) { - socket[SOCKET_CREATED_TIME] = Date.now(); - } - // don't show the hole '-----BEGIN CERTIFICATE----' key string - socket[SOCKET_NAME] = `sock[${this[CREATE_ID]()}#${options._agentKey}]`.split('-----BEGIN', 1)[0]; - socket[SOCKET_REQUEST_COUNT] = 1; - socket[SOCKET_REQUEST_FINISHED_COUNT] = 0; - installListeners(this, socket, options); - } - - createConnection(options, oncreate) { - let called = false; - const onNewCreate = (err, socket) => { - if (called) return; - called = true; - - if (err) { - this.createSocketErrorCount++; - return oncreate(err); - } - this[INIT_SOCKET](socket, options); - oncreate(err, socket); - }; - - const newSocket = super.createConnection(options, onNewCreate); - if (newSocket) onNewCreate(null, newSocket); - return newSocket; - } - - get statusChanged() { - const changed = this.createSocketCount !== this.createSocketCountLastCheck || - this.createSocketErrorCount !== this.createSocketErrorCountLastCheck || - this.closeSocketCount !== this.closeSocketCountLastCheck || - this.errorSocketCount !== this.errorSocketCountLastCheck || - this.timeoutSocketCount !== this.timeoutSocketCountLastCheck || - this.requestCount !== this.requestCountLastCheck; - if (changed) { - this.createSocketCountLastCheck = this.createSocketCount; - this.createSocketErrorCountLastCheck = this.createSocketErrorCount; - this.closeSocketCountLastCheck = this.closeSocketCount; - this.errorSocketCountLastCheck = this.errorSocketCount; - this.timeoutSocketCountLastCheck = this.timeoutSocketCount; - this.requestCountLastCheck = this.requestCount; - } - return changed; - } - - getCurrentStatus() { - return { - createSocketCount: this.createSocketCount, - createSocketErrorCount: this.createSocketErrorCount, - closeSocketCount: this.closeSocketCount, - errorSocketCount: this.errorSocketCount, - timeoutSocketCount: this.timeoutSocketCount, - requestCount: this.requestCount, - freeSockets: inspect(this.freeSockets), - sockets: inspect(this.sockets), - requests: inspect(this.requests), - }; - } -} - -// node 8 don't has timeout attribute on socket -// https://github.com/nodejs/node/pull/21204/files#diff-e6ef024c3775d787c38487a6309e491dR408 -function getSocketTimeout(socket) { - return socket.timeout || socket._idleTimeout; -} - -function installListeners(agent, socket, options) { - debug('%s create, timeout %sms', socket[SOCKET_NAME], getSocketTimeout(socket)); - - // listener socket events: close, timeout, error, free - function onFree() { - // create and socket.emit('free') logic - // https://github.com/nodejs/node/blob/master/lib/_http_agent.js#L311 - // no req on the socket, it should be the new socket - if (!socket._httpMessage && socket[SOCKET_REQUEST_COUNT] === 1) return; - - socket[SOCKET_REQUEST_FINISHED_COUNT]++; - agent.requestCount++; - debug('%s(requests: %s, finished: %s) free', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]); - - // should reuse on pedding requests? - const name = agent.getName(options); - if (socket.writable && agent.requests[name] && agent.requests[name].length) { - // will be reuse on agent free listener - socket[SOCKET_REQUEST_COUNT]++; - debug('%s(requests: %s, finished: %s) will be reuse on agent free event', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]); - } - } - socket.on('free', onFree); - - function onClose(isError) { - debug('%s(requests: %s, finished: %s) close, isError: %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], isError); - agent.closeSocketCount++; - } - socket.on('close', onClose); - - // start socket timeout handler - function onTimeout() { - // onTimeout and emitRequestTimeout(_http_client.js) - // https://github.com/nodejs/node/blob/v12.x/lib/_http_client.js#L711 - const listenerCount = socket.listeners('timeout').length; - // node <= 10, default listenerCount is 1, onTimeout - // 11 < node <= 12, default listenerCount is 2, onTimeout and emitRequestTimeout - // node >= 13, default listenerCount is 3, onTimeout, - // onTimeout(https://github.com/nodejs/node/pull/32000/files#diff-5f7fb0850412c6be189faeddea6c5359R333) - // and emitRequestTimeout - const timeout = getSocketTimeout(socket); - const req = socket._httpMessage; - const reqTimeoutListenerCount = req && req.listeners('timeout').length || 0; - debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], - timeout, listenerCount, defaultTimeoutListenerCount, !!req, reqTimeoutListenerCount); - if (debug.enabled) { - debug('timeout listeners: %s', socket.listeners('timeout').map(f => f.name).join(', ')); - } - agent.timeoutSocketCount++; - const name = agent.getName(options); - if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) { - // free socket timeout, destroy quietly - socket.destroy(); - // Remove it from freeSockets list immediately to prevent new requests - // from being sent through this socket. - agent.removeSocket(socket, options); - debug('%s is free, destroy quietly', socket[SOCKET_NAME]); - } else { - // if there is no any request socket timeout handler, - // agent need to handle socket timeout itself. - // - // custom request socket timeout handle logic must follow these rules: - // 1. Destroy socket first - // 2. Must emit socket 'agentRemove' event tell agent remove socket - // from freeSockets list immediately. - // Otherise you may be get 'socket hang up' error when reuse - // free socket and timeout happen in the same time. - if (reqTimeoutListenerCount === 0) { - const error = new Error('Socket timeout'); - error.code = 'ERR_SOCKET_TIMEOUT'; - error.timeout = timeout; - // must manually call socket.end() or socket.destroy() to end the connection. - // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback - socket.destroy(error); - agent.removeSocket(socket, options); - debug('%s destroy with timeout error', socket[SOCKET_NAME]); - } - } - } - socket.on('timeout', onTimeout); - - function onError(err) { - const listenerCount = socket.listeners('error').length; - debug('%s(requests: %s, finished: %s) error: %s, listenerCount: %s', - socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], - err, listenerCount); - agent.errorSocketCount++; - if (listenerCount === 1) { - // if socket don't contain error event handler, don't catch it, emit it again - debug('%s emit uncaught error event', socket[SOCKET_NAME]); - socket.removeListener('error', onError); - socket.emit('error', err); - } - } - socket.on('error', onError); - - function onRemove() { - debug('%s(requests: %s, finished: %s) agentRemove', - socket[SOCKET_NAME], - socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT]); - // We need this function for cases like HTTP 'upgrade' - // (defined by WebSockets) where we need to remove a socket from the - // pool because it'll be locked up indefinitely - socket.removeListener('close', onClose); - socket.removeListener('error', onError); - socket.removeListener('free', onFree); - socket.removeListener('timeout', onTimeout); - socket.removeListener('agentRemove', onRemove); - } - socket.on('agentRemove', onRemove); -} - -module.exports = Agent; - -function inspect(obj) { - const res = {}; - for (const key in obj) { - res[key] = obj[key].length; - } - return res; -} - - -/***/ }), - -/***/ 6160: -/***/ ((module) => { - - - -module.exports = { - // agent - CURRENT_ID: Symbol('agentkeepalive#currentId'), - CREATE_ID: Symbol('agentkeepalive#createId'), - INIT_SOCKET: Symbol('agentkeepalive#initSocket'), - CREATE_HTTPS_CONNECTION: Symbol('agentkeepalive#createHttpsConnection'), - // socket - SOCKET_CREATED_TIME: Symbol('agentkeepalive#socketCreatedTime'), - SOCKET_NAME: Symbol('agentkeepalive#socketName'), - SOCKET_REQUEST_COUNT: Symbol('agentkeepalive#socketRequestCount'), - SOCKET_REQUEST_FINISHED_COUNT: Symbol('agentkeepalive#socketRequestFinishedCount'), -}; - - -/***/ }), - -/***/ 414: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const OriginalHttpsAgent = (__nccwpck_require__(5692).Agent); -const HttpAgent = __nccwpck_require__(2532); -const { - INIT_SOCKET, - CREATE_HTTPS_CONNECTION, -} = __nccwpck_require__(6160); - -class HttpsAgent extends HttpAgent { - constructor(options) { - super(options); - - this.defaultPort = 443; - this.protocol = 'https:'; - this.maxCachedSessions = this.options.maxCachedSessions; - /* istanbul ignore next */ - if (this.maxCachedSessions === undefined) { - this.maxCachedSessions = 100; - } - - this._sessionCache = { - map: {}, - list: [], - }; - } - - createConnection(options, oncreate) { - const socket = this[CREATE_HTTPS_CONNECTION](options, oncreate); - this[INIT_SOCKET](socket, options); - return socket; - } -} - -// https://github.com/nodejs/node/blob/master/lib/https.js#L89 -HttpsAgent.prototype[CREATE_HTTPS_CONNECTION] = OriginalHttpsAgent.prototype.createConnection; - -[ - 'getName', - '_getSession', - '_cacheSession', - // https://github.com/nodejs/node/pull/4982 - '_evictSession', -].forEach(function(method) { - /* istanbul ignore next */ - if (typeof OriginalHttpsAgent.prototype[method] === 'function') { - HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method]; - } -}); - -module.exports = HttpsAgent; - - /***/ }), /***/ 8793: @@ -26089,1105 +25453,227 @@ exports.Deprecation = Deprecation; /***/ }), -/***/ 6577: -/***/ ((module, exports) => { +/***/ 877: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * @author Toru Nagashima - * @copyright 2015 Toru Nagashima. All rights reserved. - * See LICENSE file in root directory for full license. +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * @typedef {object} PrivateData - * @property {EventTarget} eventTarget The event target. - * @property {{type:string}} event The original event object. - * @property {number} eventPhase The current event phase. - * @property {EventTarget|null} currentTarget The current event target. - * @property {boolean} canceled The flag to prevent default. - * @property {boolean} stopped The flag to stop propagation. - * @property {boolean} immediateStopped The flag to stop propagation immediately. - * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. - * @property {number} timeStamp The unix time. - * @private - */ +const util = __nccwpck_require__(9023); +const toRegexRange = __nccwpck_require__(7551); -/** - * Private data for event wrappers. - * @type {WeakMap} - * @private - */ -const privateData = new WeakMap(); +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); -/** - * Cache for wrapper classes. - * @type {WeakMap} - * @private - */ -const wrappers = new WeakMap(); +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; -/** - * Get private data. - * @param {Event} event The event object to get private data. - * @returns {PrivateData} The private data of the event. - * @private - */ -function pd(event) { - const retv = privateData.get(event); - console.assert( - retv != null, - "'this' is expected an Event object, but got", - event - ); - return retv -} +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; -/** - * https://dom.spec.whatwg.org/#set-the-canceled-flag - * @param data {PrivateData} private data. - */ -function setCancelFlag(data) { - if (data.passiveListener != null) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error( - "Unable to preventDefault inside passive event listener invocation.", - data.passiveListener - ); - } - return - } - if (!data.event.cancelable) { - return - } +const isNumber = num => Number.isInteger(+num); - data.canceled = true; - if (typeof data.event.preventDefault === "function") { - data.event.preventDefault(); - } -} +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; -/** - * @see https://dom.spec.whatwg.org/#interface-event - * @private - */ -/** - * The event wrapper. - * @constructor - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Event|{type:string}} event The original event to wrap. - */ -function Event(eventTarget, event) { - privateData.set(this, { - eventTarget, - event, - eventPhase: 2, - currentTarget: eventTarget, - canceled: false, - stopped: false, - immediateStopped: false, - passiveListener: null, - timeStamp: event.timeStamp || Date.now(), - }); +const stringify = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; - // https://heycam.github.io/webidl/#Unforgeable - Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; - // Define accessors - const keys = Object.keys(event); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in this)) { - Object.defineProperty(this, key, defineRedirectDescriptor(key)); - } - } -} +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; -// Should be enumerable, but class methods are not enumerable. -Event.prototype = { - /** - * The type of this event. - * @type {string} - */ - get type() { - return pd(this).event.type - }, +const toSequence = (parts, options, maxLen) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - /** - * The target of this event. - * @type {EventTarget} - */ - get target() { - return pd(this).eventTarget - }, + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; - /** - * The target of this event. - * @type {EventTarget} - */ - get currentTarget() { - return pd(this).currentTarget - }, + if (parts.positives.length) { + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); + } - /** - * @returns {EventTarget[]} The composed path of this event. - */ - composedPath() { - const currentTarget = pd(this).currentTarget; - if (currentTarget == null) { - return [] - } - return [currentTarget] - }, + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; + } - /** - * Constant of NONE. - * @type {number} - */ - get NONE() { - return 0 - }, + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } - /** - * Constant of CAPTURING_PHASE. - * @type {number} - */ - get CAPTURING_PHASE() { - return 1 - }, + if (options.wrap) { + return `(${prefix}${result})`; + } - /** - * Constant of AT_TARGET. - * @type {number} - */ - get AT_TARGET() { - return 2 - }, + return result; +}; - /** - * Constant of BUBBLING_PHASE. - * @type {number} - */ - get BUBBLING_PHASE() { - return 3 - }, +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } - /** - * The target of this event. - * @type {number} - */ - get eventPhase() { - return pd(this).eventPhase - }, + let start = String.fromCharCode(a); + if (a === b) return start; - /** - * Stop event bubbling. - * @returns {void} - */ - stopPropagation() { - const data = pd(this); + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; - data.stopped = true; - if (typeof data.event.stopPropagation === "function") { - data.event.stopPropagation(); - } - }, +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; - /** - * Stop event bubbling. - * @returns {void} - */ - stopImmediatePropagation() { - const data = pd(this); +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util.inspect(...args)); +}; - data.stopped = true; - data.immediateStopped = true; - if (typeof data.event.stopImmediatePropagation === "function") { - data.event.stopImmediatePropagation(); - } - }, +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; - /** - * The flag to be bubbling. - * @type {boolean} - */ - get bubbles() { - return Boolean(pd(this).event.bubbles) - }, +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; - /** - * The flag to be cancelable. - * @type {boolean} - */ - get cancelable() { - return Boolean(pd(this).event.cancelable) - }, +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); - /** - * Cancel this event. - * @returns {void} - */ - preventDefault() { - setCancelFlag(pd(this)); - }, + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } - /** - * The flag to indicate cancellation state. - * @type {boolean} - */ - get defaultPrevented() { - return pd(this).canceled - }, + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; - /** - * The flag to be composed. - * @type {boolean} - */ - get composed() { - return Boolean(pd(this).event.composed) - }, + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); - /** - * The unix time of this event. - * @type {number} - */ - get timeStamp() { - return pd(this).timeStamp - }, + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify(start, end, options) === false; + let format = options.transform || transform(toNumber); - /** - * The target of this event. - * @type {EventTarget} - * @deprecated - */ - get srcElement() { - return pd(this).eventTarget - }, + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } - /** - * The flag to stop event bubbling. - * @type {boolean} - * @deprecated - */ - get cancelBubble() { - return pd(this).stopped - }, - set cancelBubble(value) { - if (!value) { - return - } - const data = pd(this); + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; - data.stopped = true; - if (typeof data.event.cancelBubble === "boolean") { - data.event.cancelBubble = true; - } - }, + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } - /** - * The flag to indicate cancellation state. - * @type {boolean} - * @deprecated - */ - get returnValue() { - return !pd(this).canceled - }, - set returnValue(value) { - if (!value) { - setCancelFlag(pd(this)); - } - }, + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options, maxLen) + : toRegex(range, null, { wrap: false, ...options }); + } - /** - * Initialize this event object. But do nothing under event dispatching. - * @param {string} type The event type. - * @param {boolean} [bubbles=false] The flag to be possible to bubble up. - * @param {boolean} [cancelable=false] The flag to be possible to cancel. - * @deprecated - */ - initEvent() { - // Do nothing. - }, + return range; }; -// `constructor` is not enumerable. -Object.defineProperty(Event.prototype, "constructor", { - value: Event, - configurable: true, - writable: true, -}); - -// Ensure `event instanceof window.Event` is `true`. -if (typeof window !== "undefined" && typeof window.Event !== "undefined") { - Object.setPrototypeOf(Event.prototype, window.Event.prototype); +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } - // Make association for wrappers. - wrappers.set(window.Event.prototype, Event); -} + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); -/** - * Get the property descriptor to redirect a given property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to redirect the property. - * @private - */ -function defineRedirectDescriptor(key) { - return { - get() { - return pd(this).event[key] - }, - set(value) { - pd(this).event[key] = value; - }, - configurable: true, - enumerable: true, - } -} + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); -/** - * Get the property descriptor to call a given method property. - * @param {string} key Property name to define property descriptor. - * @returns {PropertyDescriptor} The property descriptor to call the method property. - * @private - */ -function defineCallDescriptor(key) { - return { - value() { - const event = pd(this).event; - return event[key].apply(event, arguments) - }, - configurable: true, - enumerable: true, - } -} + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } -/** - * Define new wrapper class. - * @param {Function} BaseEvent The base wrapper class. - * @param {Object} proto The prototype of the original event. - * @returns {Function} The defined wrapper class. - * @private - */ -function defineWrapper(BaseEvent, proto) { - const keys = Object.keys(proto); - if (keys.length === 0) { - return BaseEvent - } + let range = []; + let index = 0; - /** CustomEvent */ - function CustomEvent(eventTarget, event) { - BaseEvent.call(this, eventTarget, event); - } + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } - CustomEvent.prototype = Object.create(BaseEvent.prototype, { - constructor: { value: CustomEvent, configurable: true, writable: true }, - }); + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } - // Define accessors. - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (!(key in BaseEvent.prototype)) { - const descriptor = Object.getOwnPropertyDescriptor(proto, key); - const isFunc = typeof descriptor.value === "function"; - Object.defineProperty( - CustomEvent.prototype, - key, - isFunc - ? defineCallDescriptor(key) - : defineRedirectDescriptor(key) - ); - } - } + return range; +}; - return CustomEvent -} - -/** - * Get the wrapper class of a given prototype. - * @param {Object} proto The prototype of the original event to get its wrapper. - * @returns {Function} The wrapper class. - * @private - */ -function getWrapper(proto) { - if (proto == null || proto === Object.prototype) { - return Event - } - - let wrapper = wrappers.get(proto); - if (wrapper == null) { - wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); - wrappers.set(proto, wrapper); - } - return wrapper -} - -/** - * Wrap a given event to management a dispatching. - * @param {EventTarget} eventTarget The event target of this dispatching. - * @param {Object} event The event to wrap. - * @returns {Event} The wrapper instance. - * @private - */ -function wrapEvent(eventTarget, event) { - const Wrapper = getWrapper(Object.getPrototypeOf(event)); - return new Wrapper(eventTarget, event) -} - -/** - * Get the immediateStopped flag of a given event. - * @param {Event} event The event to get. - * @returns {boolean} The flag to stop propagation immediately. - * @private - */ -function isStopped(event) { - return pd(event).immediateStopped -} - -/** - * Set the current event phase of a given event. - * @param {Event} event The event to set current target. - * @param {number} eventPhase New event phase. - * @returns {void} - * @private - */ -function setEventPhase(event, eventPhase) { - pd(event).eventPhase = eventPhase; -} - -/** - * Set the current target of a given event. - * @param {Event} event The event to set current target. - * @param {EventTarget|null} currentTarget New current target. - * @returns {void} - * @private - */ -function setCurrentTarget(event, currentTarget) { - pd(event).currentTarget = currentTarget; -} - -/** - * Set a passive listener of a given event. - * @param {Event} event The event to set current target. - * @param {Function|null} passiveListener New passive listener. - * @returns {void} - * @private - */ -function setPassiveListener(event, passiveListener) { - pd(event).passiveListener = passiveListener; -} - -/** - * @typedef {object} ListenerNode - * @property {Function} listener - * @property {1|2|3} listenerType - * @property {boolean} passive - * @property {boolean} once - * @property {ListenerNode|null} next - * @private - */ - -/** - * @type {WeakMap>} - * @private - */ -const listenersMap = new WeakMap(); - -// Listener types -const CAPTURE = 1; -const BUBBLE = 2; -const ATTRIBUTE = 3; - -/** - * Check whether a given value is an object or not. - * @param {any} x The value to check. - * @returns {boolean} `true` if the value is an object. - */ -function isObject(x) { - return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax -} - -/** - * Get listeners. - * @param {EventTarget} eventTarget The event target to get. - * @returns {Map} The listeners. - * @private - */ -function getListeners(eventTarget) { - const listeners = listenersMap.get(eventTarget); - if (listeners == null) { - throw new TypeError( - "'this' is expected an EventTarget object, but got another value." - ) - } - return listeners -} - -/** - * Get the property descriptor for the event attribute of a given event. - * @param {string} eventName The event name to get property descriptor. - * @returns {PropertyDescriptor} The property descriptor. - * @private - */ -function defineEventAttributeDescriptor(eventName) { - return { - get() { - const listeners = getListeners(this); - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - return node.listener - } - node = node.next; - } - return null - }, - - set(listener) { - if (typeof listener !== "function" && !isObject(listener)) { - listener = null; // eslint-disable-line no-param-reassign - } - const listeners = getListeners(this); - - // Traverse to the tail while removing old value. - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if (node.listenerType === ATTRIBUTE) { - // Remove old value. - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - node = node.next; - } - - // Add new value. - if (listener !== null) { - const newNode = { - listener, - listenerType: ATTRIBUTE, - passive: false, - once: false, - next: null, - }; - if (prev === null) { - listeners.set(eventName, newNode); - } else { - prev.next = newNode; - } - } - }, - configurable: true, - enumerable: true, - } -} - -/** - * Define an event attribute (e.g. `eventTarget.onclick`). - * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. - * @param {string} eventName The event name to define. - * @returns {void} - */ -function defineEventAttribute(eventTargetPrototype, eventName) { - Object.defineProperty( - eventTargetPrototype, - `on${eventName}`, - defineEventAttributeDescriptor(eventName) - ); -} - -/** - * Define a custom EventTarget with event attributes. - * @param {string[]} eventNames Event names for event attributes. - * @returns {EventTarget} The custom EventTarget. - * @private - */ -function defineCustomEventTarget(eventNames) { - /** CustomEventTarget */ - function CustomEventTarget() { - EventTarget.call(this); - } - - CustomEventTarget.prototype = Object.create(EventTarget.prototype, { - constructor: { - value: CustomEventTarget, - configurable: true, - writable: true, - }, - }); - - for (let i = 0; i < eventNames.length; ++i) { - defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); - } - - return CustomEventTarget -} - -/** - * EventTarget. - * - * - This is constructor if no arguments. - * - This is a function which returns a CustomEventTarget constructor if there are arguments. - * - * For example: - * - * class A extends EventTarget {} - * class B extends EventTarget("message") {} - * class C extends EventTarget("message", "error") {} - * class D extends EventTarget(["message", "error"]) {} - */ -function EventTarget() { - /*eslint-disable consistent-return */ - if (this instanceof EventTarget) { - listenersMap.set(this, new Map()); - return - } - if (arguments.length === 1 && Array.isArray(arguments[0])) { - return defineCustomEventTarget(arguments[0]) - } - if (arguments.length > 0) { - const types = new Array(arguments.length); - for (let i = 0; i < arguments.length; ++i) { - types[i] = arguments[i]; - } - return defineCustomEventTarget(types) - } - throw new TypeError("Cannot call a class as a function") - /*eslint-enable consistent-return */ -} - -// Should be enumerable, but class methods are not enumerable. -EventTarget.prototype = { - /** - * Add a given listener to this event target. - * @param {string} eventName The event name to add. - * @param {Function} listener The listener to add. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - addEventListener(eventName, listener, options) { - if (listener == null) { - return - } - if (typeof listener !== "function" && !isObject(listener)) { - throw new TypeError("'listener' should be a function or an object.") - } - - const listeners = getListeners(this); - const optionsIsObj = isObject(options); - const capture = optionsIsObj - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - const newNode = { - listener, - listenerType, - passive: optionsIsObj && Boolean(options.passive), - once: optionsIsObj && Boolean(options.once), - next: null, - }; - - // Set it as the first node if the first node is null. - let node = listeners.get(eventName); - if (node === undefined) { - listeners.set(eventName, newNode); - return - } - - // Traverse to the tail while checking duplication.. - let prev = null; - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - // Should ignore duplication. - return - } - prev = node; - node = node.next; - } - - // Add it. - prev.next = newNode; - }, - - /** - * Remove a given listener from this event target. - * @param {string} eventName The event name to remove. - * @param {Function} listener The listener to remove. - * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. - * @returns {void} - */ - removeEventListener(eventName, listener, options) { - if (listener == null) { - return - } - - const listeners = getListeners(this); - const capture = isObject(options) - ? Boolean(options.capture) - : Boolean(options); - const listenerType = capture ? CAPTURE : BUBBLE; - - let prev = null; - let node = listeners.get(eventName); - while (node != null) { - if ( - node.listener === listener && - node.listenerType === listenerType - ) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - return - } - - prev = node; - node = node.next; - } - }, - - /** - * Dispatch a given event. - * @param {Event|{type:string}} event The event to dispatch. - * @returns {boolean} `false` if canceled. - */ - dispatchEvent(event) { - if (event == null || typeof event.type !== "string") { - throw new TypeError('"event.type" should be a string.') - } - - // If listeners aren't registered, terminate. - const listeners = getListeners(this); - const eventName = event.type; - let node = listeners.get(eventName); - if (node == null) { - return true - } - - // Since we cannot rewrite several properties, so wrap object. - const wrappedEvent = wrapEvent(this, event); - - // This doesn't process capturing phase and bubbling phase. - // This isn't participating in a tree. - let prev = null; - while (node != null) { - // Remove this listener if it's once - if (node.once) { - if (prev !== null) { - prev.next = node.next; - } else if (node.next !== null) { - listeners.set(eventName, node.next); - } else { - listeners.delete(eventName); - } - } else { - prev = node; - } - - // Call this listener - setPassiveListener( - wrappedEvent, - node.passive ? node.listener : null - ); - if (typeof node.listener === "function") { - try { - node.listener.call(this, wrappedEvent); - } catch (err) { - if ( - typeof console !== "undefined" && - typeof console.error === "function" - ) { - console.error(err); - } - } - } else if ( - node.listenerType !== ATTRIBUTE && - typeof node.listener.handleEvent === "function" - ) { - node.listener.handleEvent(wrappedEvent); - } - - // Break if `event.stopImmediatePropagation` was called. - if (isStopped(wrappedEvent)) { - break - } - - node = node.next; - } - setPassiveListener(wrappedEvent, null); - setEventPhase(wrappedEvent, 0); - setCurrentTarget(wrappedEvent, null); - - return !wrappedEvent.defaultPrevented - }, -}; - -// `constructor` is not enumerable. -Object.defineProperty(EventTarget.prototype, "constructor", { - value: EventTarget, - configurable: true, - writable: true, -}); - -// Ensure `eventTarget instanceof window.EventTarget` is `true`. -if ( - typeof window !== "undefined" && - typeof window.EventTarget !== "undefined" -) { - Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); -} - -exports.defineEventAttribute = defineEventAttribute; -exports.EventTarget = EventTarget; -exports["default"] = EventTarget; - -module.exports = EventTarget -module.exports.EventTarget = module.exports["default"] = EventTarget -module.exports.defineEventAttribute = defineEventAttribute -//# sourceMappingURL=event-target-shim.js.map - - -/***/ }), - -/***/ 877: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * fill-range - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -const util = __nccwpck_require__(9023); -const toRegexRange = __nccwpck_require__(7551); - -const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); - -const transform = toNumber => { - return value => toNumber === true ? Number(value) : String(value); -}; - -const isValidValue = value => { - return typeof value === 'number' || (typeof value === 'string' && value !== ''); -}; - -const isNumber = num => Number.isInteger(+num); - -const zeros = input => { - let value = `${input}`; - let index = -1; - if (value[0] === '-') value = value.slice(1); - if (value === '0') return false; - while (value[++index] === '0'); - return index > 0; -}; - -const stringify = (start, end, options) => { - if (typeof start === 'string' || typeof end === 'string') { - return true; - } - return options.stringify === true; -}; - -const pad = (input, maxLength, toNumber) => { - if (maxLength > 0) { - let dash = input[0] === '-' ? '-' : ''; - if (dash) input = input.slice(1); - input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); - } - if (toNumber === false) { - return String(input); - } - return input; -}; - -const toMaxLen = (input, maxLength) => { - let negative = input[0] === '-' ? '-' : ''; - if (negative) { - input = input.slice(1); - maxLength--; - } - while (input.length < maxLength) input = '0' + input; - return negative ? ('-' + input) : input; -}; - -const toSequence = (parts, options, maxLen) => { - parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); - - let prefix = options.capture ? '' : '?:'; - let positives = ''; - let negatives = ''; - let result; - - if (parts.positives.length) { - positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); - } - - if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; - } - - if (positives && negatives) { - result = `${positives}|${negatives}`; - } else { - result = positives || negatives; - } - - if (options.wrap) { - return `(${prefix}${result})`; - } - - return result; -}; - -const toRange = (a, b, isNumbers, options) => { - if (isNumbers) { - return toRegexRange(a, b, { wrap: false, ...options }); - } - - let start = String.fromCharCode(a); - if (a === b) return start; - - let stop = String.fromCharCode(b); - return `[${start}-${stop}]`; -}; - -const toRegex = (start, end, options) => { - if (Array.isArray(start)) { - let wrap = options.wrap === true; - let prefix = options.capture ? '' : '?:'; - return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); - } - return toRegexRange(start, end, options); -}; - -const rangeError = (...args) => { - return new RangeError('Invalid range arguments: ' + util.inspect(...args)); -}; - -const invalidRange = (start, end, options) => { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; -}; - -const invalidStep = (step, options) => { - if (options.strictRanges === true) { - throw new TypeError(`Expected step "${step}" to be a number`); - } - return []; -}; - -const fillNumbers = (start, end, step = 1, options = {}) => { - let a = Number(start); - let b = Number(end); - - if (!Number.isInteger(a) || !Number.isInteger(b)) { - if (options.strictRanges === true) throw rangeError([start, end]); - return []; - } - - // fix negative zero - if (a === 0) a = 0; - if (b === 0) b = 0; - - let descending = a > b; - let startString = String(start); - let endString = String(end); - let stepString = String(step); - step = Math.max(Math.abs(step), 1); - - let padded = zeros(startString) || zeros(endString) || zeros(stepString); - let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; - let toNumber = padded === false && stringify(start, end, options) === false; - let format = options.transform || transform(toNumber); - - if (options.toRegex && step === 1) { - return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); - } - - let parts = { negatives: [], positives: [] }; - let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); - let range = []; - let index = 0; - - while (descending ? a >= b : a <= b) { - if (options.toRegex === true && step > 1) { - push(a); - } else { - range.push(pad(format(a, index), maxLen, toNumber)); - } - a = descending ? a - step : a + step; - index++; - } - - if (options.toRegex === true) { - return step > 1 - ? toSequence(parts, options, maxLen) - : toRegex(range, null, { wrap: false, ...options }); - } - - return range; -}; - -const fillLetters = (start, end, step = 1, options = {}) => { - if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { - return invalidRange(start, end, options); - } - - let format = options.transform || (val => String.fromCharCode(val)); - let a = `${start}`.charCodeAt(0); - let b = `${end}`.charCodeAt(0); - - let descending = a > b; - let min = Math.min(a, b); - let max = Math.max(a, b); - - if (options.toRegex && step === 1) { - return toRange(min, max, false, options); - } - - let range = []; - let index = 0; - - while (descending ? a >= b : a <= b) { - range.push(format(a, index)); - a = descending ? a - step : a + step; - index++; - } - - if (options.toRegex === true) { - return toRegex(range, null, { wrap: false, options }); - } - - return range; -}; - -const fill = (start, end, step, options = {}) => { - if (end == null && isValidValue(start)) { - return [start]; - } +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } if (!isValidValue(start) || !isValidValue(end)) { return invalidRange(start, end, options); @@ -27220,37 +25706,6 @@ const fill = (start, end, step, options = {}) => { module.exports = fill; -/***/ }), - -/***/ 3724: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * humanize-ms - index.js - * Copyright(c) 2014 dead_horse - * MIT Licensed - */ - - - -/** - * Module dependencies. - */ - -var util = __nccwpck_require__(9023); -var ms = __nccwpck_require__(744); - -module.exports = function (t) { - if (typeof t === 'number') return t; - var r = ms(t); - if (r === undefined) { - var err = new Error(util.format('humanize-ms(%j) result undefined', t)); - console.warn(err.stack); - } - return r; -}; - - /***/ }), /***/ 3102: @@ -27759,9121 +26214,7740 @@ module.exports = micromatch; /***/ }), -/***/ 744: -/***/ ((module) => { - -/** - * 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) - ); -}; +/***/ 5560: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +var wrappy = __nccwpck_require__(8264) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -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; - } -} +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) -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'; +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) } - return ms + 'ms'; + f.called = false + return f } -/** - * 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'); +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) } - 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' : ''); + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f } /***/ }), -/***/ 6705: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 2766: +/***/ ((module) => { +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - -var Stream = _interopDefault(__nccwpck_require__(2203)); -var http = _interopDefault(__nccwpck_require__(8611)); -var Url = _interopDefault(__nccwpck_require__(7016)); -var whatwgUrl = _interopDefault(__nccwpck_require__(2686)); -var https = _interopDefault(__nccwpck_require__(5692)); -var zlib = _interopDefault(__nccwpck_require__(3106)); - -// 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); + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; - 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 } -}); +/***/ 6459: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const EventEmitter = __nccwpck_require__(301); +const p_timeout_1 = __nccwpck_require__(4802); +const priority_queue_1 = __nccwpck_require__(5905); +// eslint-disable-next-line @typescript-eslint/no-empty-function +const empty = () => { }; +const timeoutError = new p_timeout_1.TimeoutError(); /** - * fetch-error.js - * - * FetchError interface for operational errors - */ +Promise queue with concurrency control. +*/ +class PQueue extends EventEmitter { + constructor(options) { + var _a, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); + } + if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit('next'); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit('idle'); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = undefined; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === undefined) { + const delay = this._intervalEnd - now; + if (delay < 0) { + // Act as the interval was done + // We don't need to resume it here because it will be resumed on line 160 + this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; + } + else { + // Act as the interval is pending + if (this._timeoutId === undefined) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + // We can clear the interval ("pause") + // Because we can redo it later ("resume") + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = undefined; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit('active'); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== undefined) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = undefined; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + // eslint-disable-next-line no-empty + while (this._tryToStartAnother()) { } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { + if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return undefined; + }); + resolve(await operation); + } + catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit('add'); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. -/** - * 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); + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. - this.message = message; - this.type = type; + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + // Instantly resolve if the queue is empty + if (this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + // Instantly resolve if none pending and if nothing else is queued + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } } +exports["default"] = PQueue; -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; - -let convert; -try { - convert = (__nccwpck_require__(2078).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; +/***/ 9015: +/***/ ((__unused_webpack_module, exports) => { -/** - * 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; - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound +// Used to compute insertion index to keep queue sorted after insertion +function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = (count / 2) | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; + } + else { + count = step; + } + } + return first; } +exports["default"] = lowerBound; -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)); - } +/***/ 5905: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // 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)); - } - }); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lower_bound_1 = __nccwpck_require__(9015); +class PriorityQueue { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } +} +exports["default"] = PriorityQueue; - 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); - }); +/***/ 301: +/***/ ((module) => { - 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)); - } - }); - }); -} +var has = Object.prototype.hasOwnProperty + , prefix = '~'; /** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String + * @constructor + * @private */ -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; - } + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; - /** - * 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]; - } - } + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } + return ee; +}; - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; - /** - * 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]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; -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 } -}); + if (!this._events[evt]) return false; -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + var listeners = this._events[evt] + , len = arguments.length + , args + , i; - 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(', ')]; - }); -} + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); -const INTERNAL = Symbol('internal'); + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; - 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 - }; - } + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - this[INTERNAL].index = index + 1; + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + listeners[i].fn.apply(listeners[i].context, args); + } + } + } -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); + return true; +}; /** - * Export the Headers object in a form that Node.js can consume. + * Add a listener for a given event. * - * @param Headers headers - * @return Object + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public */ -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; -} +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; /** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. + * Add a one-time listener for a given event. * - * @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; + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; /** - * Response class + * Remove the listeners of a given event. * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; - Body.call(this, body, opts); + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } - const status = opts.status || 200; - const headers = new Headers(opts.headers); + var listeners = this._events[evt]; - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } - get url() { - return this[INTERNALS$1].url || ''; - } + return this; +}; - get status() { - return this[INTERNALS$1].status; - } +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } - get redirected() { - return this[INTERNALS$1].counter > 0; - } + return this; +}; - get statusText() { - return this[INTERNALS$1].statusText; - } +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; - get headers() { - return this[INTERNALS$1].headers; - } +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; - /** - * 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 - }); - } +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; } -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 -}); +/***/ 2103: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -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; +const retry = __nccwpck_require__(5546); -/** - * 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(); - } +const networkErrorMsgs = [ + 'Failed to fetch', // Chrome + 'NetworkError when attempting to fetch resource.', // Firefox + 'The Internet connection appears to be offline.', // Safari + 'Network request failed' // `cross-fetch` +]; - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); -} +class AbortError extends Error { + constructor(message) { + super(); -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + if (message instanceof Error) { + this.originalError = message; + ({message} = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } -/** - * 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'; + this.name = 'AbortError'; + this.message = message; + } } -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); -} +const decorateErrorWithCounts = (error, attemptNumber, options) => { + // Minus 1 from attemptNumber because the first attempt does not count as a retry + const retriesLeft = options.retries - (attemptNumber - 1); -/** - * 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); - } + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; +}; - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } +const pRetry = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => {}, + retries: 10, + ...options + }; - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + const operation = retry.operation(options); - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); + operation.attempt(async attemptNumber => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); - const headers = new Headers(init.headers || input.headers || {}); + try { + await options.onFailedAttempt(error); + } catch (error) { + reject(error); + return; + } - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); + if (!operation.retry(error)) { + reject(operation.mainError()); + } } } + }); +}); - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; +module.exports = pRetry; +// TODO: remove this in the next major version +module.exports["default"] = pRetry; - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } +module.exports.AbortError = AbortError; - 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); - } +/***/ 4802: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get headers() { - return this[INTERNALS$2].headers; - } - get redirect() { - return this[INTERNALS$2].redirect; - } - get signal() { - return this[INTERNALS$2].signal; - } +const pFinally = __nccwpck_require__(2766); - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); +class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; } } -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'); +const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== 'number' || milliseconds < 0) { + throw new TypeError('Expected `milliseconds` to be a positive number'); } - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); + if (milliseconds === Infinity) { + resolve(promise); + return; } - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } + const timer = setTimeout(() => { + if (typeof fallback === 'function') { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } - // 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); + return; } - } - 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 - }); -} + const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ + if (typeof promise.cancel === 'function') { + promise.cancel(); + } -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); + reject(timeoutError); + }, milliseconds); - this.type = 'aborted'; - this.message = message; + // TODO: Use native `finally` keyword when targeting Node.js 10 + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); +}); - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} +module.exports = pTimeout; +// TODO: Remove this for the next major release +module.exports["default"] = pTimeout; -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; +module.exports.TimeoutError = TimeoutError; -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; +/***/ 2673: +/***/ ((module) => { - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; +function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e2){throw _e2},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e3){didErr=true;err=_e3},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return _typeof(key)==="symbol"?key:String(key)}function _toPrimitive(input,hint){if(_typeof(input)!=="object"||input===null)return input;var prim=input[Symbol.toPrimitive];if(prim!==undefined){var res=prim.call(input,hint||"default");if(_typeof(res)!=="object")return res;throw new TypeError("@@toPrimitive must return a primitive value.")}return(hint==="string"?String:Number)(input)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i { - // 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); +module.exports = __nccwpck_require__(8016); - 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); - }; +/***/ 5595: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (signal && signal.aborted) { - abort(); - return; - } - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; - // send request - const req = send(options); - let reqTimeout; +const path = __nccwpck_require__(6928); +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } +/** + * Posix glob regex + */ - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); +/** + * Windows glob regex + */ - if (response && response.body) { - destroyStream(response.body, err); - } +const WINDOWS_CHARS = { + ...POSIX_CHARS, - finalize(); - }); + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; - fixResponseChunkedTransferBadEnding(req, function (err) { - if (signal && signal.aborted) { - return; - } +/** + * POSIX Bracket Regex + */ - if (response && response.body) { - destroyStream(response.body, err); - } - }); +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; - /* 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); - } - }); - }); - } +module.exports = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, - req.on('response', function (res) { - clearTimeout(reqTimeout); + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, - const headers = createHeadersLenient(res.headers); + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ - // 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; - } - } + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ - // 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; - } - } + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ - // 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 - }; + CHAR_ASTERISK: 42, /* * */ - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ - // HTTP-network fetch step 12.1.1.4: handle content codings + SEP: path.sep, - // 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; - } + /** + * Create EXTGLOB_CHARS + */ - // 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 - }; + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + /** + * Create GLOB_CHARS + */ - // 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; - } + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; - // 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; +/***/ 8265: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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(); - } -} +const constants = __nccwpck_require__(5595); +const utils = __nccwpck_require__(4059); /** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean + * Constants */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; -// expose Promise -fetch.Promise = global.Promise; +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants; -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; +/** + * Helpers + */ +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } -/***/ }), + args.sort(); + const value = `[${args.join('-')}]`; -/***/ 5560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils.escapeRegex(v)).join('..'); + } -var wrappy = __nccwpck_require__(8264) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + return value; +}; -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) +/** + * Create the message for a syntax error + */ - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); } - f.called = false - return f -} -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; -/***/ }), + const capture = opts.capture ? '' : '?:'; + const win32 = utils.isWindows(options); -/***/ 2766: -/***/ ((module) => { + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants.globChars(win32); + const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + if (opts.capture) { + star = `(${star})`; + } -/***/ }), + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } -/***/ 6459: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils.removePrefix(input, state); + len = input.length; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const EventEmitter = __nccwpck_require__(301); -const p_timeout_1 = __nccwpck_require__(4802); -const priority_queue_1 = __nccwpck_require__(5905); -// eslint-disable-next-line @typescript-eslint/no-empty-function -const empty = () => { }; -const timeoutError = new p_timeout_1.TimeoutError(); -/** -Promise queue with concurrency control. -*/ -class PQueue extends EventEmitter { - constructor(options) { - var _a, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; + + if (count % 2 === 0) { + return false; } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit('next'); + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit('idle'); - } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = undefined; + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === undefined) { - const delay = this._intervalEnd - now; - if (delay < 0) { - // Act as the interval was done - // We don't need to resume it here because it will be resumed on line 160 - this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; - } - else { - // Act as the interval is pending - if (this._timeoutId === undefined) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - // We can clear the interval ("pause") - // Because we can redo it later ("resume") - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = undefined; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit('active'); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== undefined) { - return; + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - // eslint-disable-next-line no-empty - while (this._tryToStartAnother()) { } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { - if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return undefined; - }); - resolve(await operation); - } - catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit('add'); + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); }); + } } - /** - Same as `.add()`, but accepts an array of sync or async functions. - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; + if (output === input && opts.contains === true) { + state.output = input; + return state; } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); + + state.output = utils.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; } + /** - Can be called multiple times. Useful if you for example add additional items at a later time. + * Escaped characters + */ - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - // Instantly resolve if the queue is empty - if (this._queue.size === 0) { - return; + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; } - return new Promise(resolve => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } } + /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - // Instantly resolve if none pending and if nothing else is queued - if (this._pendingCount === 0 && this._queue.size === 0) { - return; + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } } - return new Promise(resolve => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. + } - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - return this._queue.filter(options).length; + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; } + /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils.escapeRegex(value); + prev.value += value; + append({ value }); + continue; } + /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; } + /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; } -} -exports["default"] = PQueue; + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } -/***/ }), + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } -/***/ 9015: -/***/ ((__unused_webpack_module, exports) => { + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + /** + * Square brackets + */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound -// Used to compute insertion index to keep queue sorted after insertion -function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = (count / 2) | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count -= step + 1; - } - else { - count = step; + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); } - } - return first; -} -exports["default"] = lowerBound; - -/***/ }), + value = `\\${value}`; + } else { + increment('brackets'); + } -/***/ 5905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + push({ type: 'bracket', value }); + continue; + } + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lower_bound_1 = __nccwpck_require__(9015); -class PriorityQueue { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); } - const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); - this._queue.splice(index, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } -} -exports["default"] = PriorityQueue; + push({ type: 'text', value, output: `\\${value}` }); + continue; + } -/***/ }), + decrement('brackets'); -/***/ 301: -/***/ ((module) => { + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + prev.value += value; + append({ value }); + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { + continue; + } -var has = Object.prototype.hasOwnProperty - , prefix = '~'; + const escaped = utils.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} + /** + * Braces + */ -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} + if (value === '{' && opts.nobrace !== true) { + increment('braces'); -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; + braces.push(open); + push(open); + continue; + } - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; + if (value === '}') { + const brace = braces[braces.length - 1]; - return emitter; -} + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} + let output = ')'; -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } - if (this._eventsCount === 0) return names; + output = expandRange(range, opts); + state.backtrack = true; + } - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } - return names; -}; + /** + * Pipes + */ -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; + /** + * Commas + */ - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } + if (value === ',') { + let output = value; - return ee; -}; + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; + push({ type: 'comma', value, output }); + continue; + } - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; + /** + * Slashes + */ -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } - if (!this._events[evt]) return false; + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } - var listeners = this._events[evt] - , len = arguments.length - , args - , i; + /** + * Dots + */ - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; } - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; + /** + * Question marks + */ - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; - listeners[i].fn.apply(listeners[i].context, args); - } - } - } + if (next === '<' && !utils.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } - return true; -}; + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; + push({ type: 'text', value, output }); + continue; + } -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; + push({ type: 'qmark', value, output: QMARK }); + continue; + } - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } + /** + * Exclamation + */ - var listeners = this._events[evt]; + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; } } - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; -}; + /** + * Plus + */ -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } - return this; -}; + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; + /** + * Plain text + */ -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; -} + push({ type: 'text', value }); + continue; + } + /** + * Plain text + */ -/***/ }), + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } -/***/ 2103: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + push({ type: 'text', value }); + continue; + } -const retry = __nccwpck_require__(5546); + /** + * Stars + */ -const networkErrorMsgs = [ - 'Failed to fetch', // Chrome - 'NetworkError when attempting to fetch resource.', // Firefox - 'The Internet connection appears to be offline.', // Safari - 'Network request failed' // `cross-fetch` -]; + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } -class AbortError extends Error { - constructor(message) { - super(); - - if (message instanceof Error) { - this.originalError = message; - ({message} = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } - - this.name = 'AbortError'; - this.message = message; - } -} - -const decorateErrorWithCounts = (error, attemptNumber, options) => { - // Minus 1 from attemptNumber because the first attempt does not count as a retry - const retriesLeft = options.retries - (attemptNumber - 1); - - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; -}; - -const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); - -const pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => {}, - retries: 10, - ...options - }; - - const operation = retry.operation(options); - - operation.attempt(async attemptNumber => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - - try { - await options.onFailedAttempt(error); - } catch (error) { - reject(error); - return; - } - - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); -}); - -module.exports = pRetry; -// TODO: remove this in the next major version -module.exports["default"] = pRetry; + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } -module.exports.AbortError = AbortError; + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); -/***/ }), + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } -/***/ 4802: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } -const pFinally = __nccwpck_require__(2766); + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } -} + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } -const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== 'number' || milliseconds < 0) { - throw new TypeError('Expected `milliseconds` to be a positive number'); - } + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; - if (milliseconds === Infinity) { - resolve(promise); - return; - } + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; - return; - } + state.output += prior.output + prev.output; + state.globstar = true; - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + consume(value + advance()); - if (typeof promise.cancel === 'function') { - promise.cancel(); - } + push({ type: 'slash', value: '/', output: '' }); + continue; + } - reject(timeoutError); - }, milliseconds); + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } - // TODO: Use native `finally` keyword when targeting Node.js 10 - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); -module.exports = pTimeout; -// TODO: Remove this for the next major release -module.exports["default"] = pTimeout; + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; -module.exports.TimeoutError = TimeoutError; + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + const token = { type: 'star', value, output: star }; -/***/ }), + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } -/***/ 2673: -/***/ ((module) => { + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } -function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e2){throw _e2},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e3){didErr=true;err=_e3},f:function f(){try{if(!normalCompletion&&it["return"]!=null)it["return"]()}finally{if(didErr)throw err}}}}function _defineProperty(obj,key,value){key=_toPropertyKey(key);if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return _typeof(key)==="symbol"?key:String(key)}function _toPrimitive(input,hint){if(_typeof(input)!=="object"||input===null)return input;var prim=input[Symbol.toPrimitive];if(prim!==undefined){var res=prim.call(input,hint||"default");if(_typeof(res)!=="object")return res;throw new TypeError("@@toPrimitive must return a primitive value.")}return(hint==="string"?String:Number)(input)}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest()}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i { + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + push(token); + } + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils.escapeLast(state.output, '['); + decrement('brackets'); + } -module.exports = __nccwpck_require__(8016); + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils.escapeLast(state.output, '('); + decrement('parens'); + } + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils.escapeLast(state.output, '{'); + decrement('braces'); + } -/***/ }), + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } -/***/ 5595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + if (token.suffix) { + state.output += token.suffix; + } + } + } -const path = __nccwpck_require__(6928); -const WIN_SLASH = '\\\\/'; -const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + return state; +}; /** - * Posix glob regex + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. */ -const DOT_LITERAL = '\\.'; -const PLUS_LITERAL = '\\+'; -const QMARK_LITERAL = '\\?'; -const SLASH_LITERAL = '\\/'; -const ONE_CHAR = '(?=.)'; -const QMARK = '[^/]'; -const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; -const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; -const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; -const NO_DOT = `(?!${DOT_LITERAL})`; -const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; -const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; -const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; -const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; -const STAR = `${QMARK}*?`; - -const POSIX_CHARS = { - DOT_LITERAL, - PLUS_LITERAL, - QMARK_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - QMARK, - END_ANCHOR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK_NO_DOT, - STAR, - START_ANCHOR -}; +parse.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } -/** - * Windows glob regex - */ + input = REPLACEMENTS[input] || input; + const win32 = utils.isWindows(options); -const WINDOWS_CHARS = { - ...POSIX_CHARS, + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants.globChars(win32); - SLASH_LITERAL: `[${WIN_SLASH}]`, - QMARK: WIN_NO_SLASH, - STAR: `${WIN_NO_SLASH}*?`, - DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, - NO_DOT: `(?!${DOT_LITERAL})`, - NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, - NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, - QMARK_NO_DOT: `[^.${WIN_SLASH}]`, - START_ANCHOR: `(?:^|[${WIN_SLASH}])`, - END_ANCHOR: `(?:[${WIN_SLASH}]|$)` -}; + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; -/** - * POSIX Bracket Regex - */ + if (opts.capture) { + star = `(${star})`; + } -const POSIX_REGEX_SOURCE = { - alnum: 'a-zA-Z0-9', - alpha: 'a-zA-Z', - ascii: '\\x00-\\x7F', - blank: ' \\t', - cntrl: '\\x00-\\x1F\\x7F', - digit: '0-9', - graph: '\\x21-\\x7E', - lower: 'a-z', - print: '\\x20-\\x7E ', - punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', - space: ' \\t\\r\\n\\v\\f', - upper: 'A-Z', - word: 'A-Za-z0-9_', - xdigit: 'A-Fa-f0-9' -}; + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; -module.exports = { - MAX_LENGTH: 1024 * 64, - POSIX_REGEX_SOURCE, + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; - // regular expressions - REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, - REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, - REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, - REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, - REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, - REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; - // Replace globs with equivalent patterns to reduce parsing time. - REPLACEMENTS: { - '***': '*', - '**/**': '**', - '**/**/**': '**' - }, + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - // Digits - CHAR_0: 48, /* 0 */ - CHAR_9: 57, /* 9 */ + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; - // Alphabet chars. - CHAR_UPPERCASE_A: 65, /* A */ - CHAR_LOWERCASE_A: 97, /* a */ - CHAR_UPPERCASE_Z: 90, /* Z */ - CHAR_LOWERCASE_Z: 122, /* z */ + case '**': + return nodot + globstar(opts); - CHAR_LEFT_PARENTHESES: 40, /* ( */ - CHAR_RIGHT_PARENTHESES: 41, /* ) */ + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; - CHAR_ASTERISK: 42, /* * */ + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; - // Non-alphabetic chars. - CHAR_AMPERSAND: 38, /* & */ - CHAR_AT: 64, /* @ */ - CHAR_BACKWARD_SLASH: 92, /* \ */ - CHAR_CARRIAGE_RETURN: 13, /* \r */ - CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ - CHAR_COLON: 58, /* : */ - CHAR_COMMA: 44, /* , */ - CHAR_DOT: 46, /* . */ - CHAR_DOUBLE_QUOTE: 34, /* " */ - CHAR_EQUAL: 61, /* = */ - CHAR_EXCLAMATION_MARK: 33, /* ! */ - CHAR_FORM_FEED: 12, /* \f */ - CHAR_FORWARD_SLASH: 47, /* / */ - CHAR_GRAVE_ACCENT: 96, /* ` */ - CHAR_HASH: 35, /* # */ - CHAR_HYPHEN_MINUS: 45, /* - */ - CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ - CHAR_LEFT_CURLY_BRACE: 123, /* { */ - CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ - CHAR_LINE_FEED: 10, /* \n */ - CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ - CHAR_PERCENT: 37, /* % */ - CHAR_PLUS: 43, /* + */ - CHAR_QUESTION_MARK: 63, /* ? */ - CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ - CHAR_RIGHT_CURLY_BRACE: 125, /* } */ - CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ - CHAR_SEMICOLON: 59, /* ; */ - CHAR_SINGLE_QUOTE: 39, /* ' */ - CHAR_SPACE: 32, /* */ - CHAR_TAB: 9, /* \t */ - CHAR_UNDERSCORE: 95, /* _ */ - CHAR_VERTICAL_LINE: 124, /* | */ - CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; - SEP: path.sep, + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; - /** - * Create EXTGLOB_CHARS - */ + const source = create(match[1]); + if (!source) return; - extglobChars(chars) { - return { - '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, - '?': { type: 'qmark', open: '(?:', close: ')?' }, - '+': { type: 'plus', open: '(?:', close: ')+' }, - '*': { type: 'star', open: '(?:', close: ')*' }, - '@': { type: 'at', open: '(?:', close: ')' } - }; - }, + return source + DOT_LITERAL + match[2]; + } + } + }; - /** - * Create GLOB_CHARS - */ + const output = utils.removePrefix(input, state); + let source = create(output); - globChars(win32) { - return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; } + + return source; }; +module.exports = parse; + /***/ }), -/***/ 8265: +/***/ 8016: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const constants = __nccwpck_require__(5595); +const path = __nccwpck_require__(6928); +const scan = __nccwpck_require__(1781); +const parse = __nccwpck_require__(8265); const utils = __nccwpck_require__(4059); +const constants = __nccwpck_require__(5595); +const isObject = val => val && typeof val === 'object' && !Array.isArray(val); /** - * Constants + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public */ -const { - MAX_LENGTH, - POSIX_REGEX_SOURCE, - REGEX_NON_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_BACKREF, - REPLACEMENTS -} = constants; +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } -/** - * Helpers - */ + const isState = isObject(glob) && glob.tokens && glob.input; -const expandRange = (args, options) => { - if (typeof options.expandRange === 'function') { - return options.expandRange(...args, options); + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); } - args.sort(); - const value = `[${args.join('-')}]`; + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState + ? picomatch.compileRe(glob, options) + : picomatch.makeRe(glob, options, false, true); - try { - /* eslint-disable-next-line no-new */ - new RegExp(value); - } catch (ex) { - return args.map(v => utils.escapeRegex(v)).join('..'); + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); } - return value; -}; + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; -/** - * Create the message for a syntax error - */ + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } -const syntaxError = (type, char) => { - return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; }; /** - * Parse the given input string. - * @param {String} input - * @param {Object} options - * @return {Object} + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public */ -const parse = (input, options) => { +picomatch.test = (input, regex, options, { glob, posix } = {}) => { if (typeof input !== 'string') { - throw new TypeError('Expected a string'); + throw new TypeError('Expected input to be a string'); } - input = REPLACEMENTS[input] || input; - - const opts = { ...options }; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - - let len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + if (input === '') { + return { isMatch: false, output: '' }; } - const bos = { type: 'bos', value: '', output: opts.prepend || '' }; - const tokens = [bos]; - - const capture = opts.capture ? '' : '?:'; - const win32 = utils.isWindows(options); - - // create constants based on platform, for windows or posix - const PLATFORM_CHARS = constants.globChars(win32); - const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS); - - const { - DOT_LITERAL, - PLUS_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOT_SLASH, - NO_DOTS_SLASH, - QMARK, - QMARK_NO_DOT, - STAR, - START_ANCHOR - } = PLATFORM_CHARS; - - const globstar = opts => { - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; - - const nodot = opts.dot ? '' : NO_DOT; - const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; - let star = opts.bash === true ? globstar(opts) : STAR; + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; - if (opts.capture) { - star = `(${star})`; + if (match === false) { + output = format ? format(input) : input; + match = output === glob; } - // minimatch options support - if (typeof opts.noext === 'boolean') { - opts.noextglob = opts.noext; + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } } - const state = { - input, - index: -1, - start: 0, - dot: opts.dot === true, - consumed: '', - output: '', - prefix: '', - backtrack: false, - negated: false, - brackets: 0, - braces: 0, - parens: 0, - quotes: 0, - globstar: false, - tokens - }; + return { isMatch: Boolean(match), match, output }; +}; - input = utils.removePrefix(input, state); - len = input.length; +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ - const extglobs = []; - const braces = []; - const stack = []; - let prev = bos; - let value; +picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path.basename(input)); +}; - /** - * Tokenizing helpers - */ +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ - const eos = () => state.index === len - 1; - const peek = state.peek = (n = 1) => input[state.index + n]; - const advance = state.advance = () => input[++state.index] || ''; - const remaining = () => input.slice(state.index + 1); - const consume = (value = '', num = 0) => { - state.consumed += value; - state.index += num; - }; +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); - const append = token => { - state.output += token.output != null ? token.output : token.value; - consume(token.value); - }; +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ - const negate = () => { - let count = 1; +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse(pattern, { ...options, fastpaths: false }); +}; - while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { - advance(); - state.start++; - count++; - } +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ - if (count % 2 === 0) { - return false; - } +picomatch.scan = (input, options) => scan(input, options); - state.negated = true; - state.start++; - return true; - }; +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ - const increment = type => { - state[type]++; - stack.push(type); - }; +picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } - const decrement = type => { - state[type]--; - stack.pop(); - }; + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; - /** - * Push tokens onto the tokens array. This helper speeds up - * tokenizing by 1) helping us avoid backtracking as much as possible, - * and 2) helping us avoid creating extra tokens when consecutive - * characters are plain text. This improves performance and simplifies - * lookbehinds. - */ + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } - const push = tok => { - if (prev.type === 'globstar') { - const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); - const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + const regex = picomatch.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } - if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { - state.output = state.output.slice(0, -prev.output.length); - prev.type = 'star'; - prev.value = '*'; - prev.output = star; - state.output += prev.output; - } - } + return regex; +}; - if (extglobs.length && tok.type !== 'paren') { - extglobs[extglobs.length - 1].inner += tok.value; - } +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ - if (tok.value || tok.output) append(tok); - if (prev && prev.type === 'text' && tok.type === 'text') { - prev.value += tok.value; - prev.output = (prev.output || '') + tok.value; - return; - } +picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } - tok.prev = prev; - tokens.push(tok); - prev = tok; - }; + let parsed = { negated: false, fastpaths: true }; - const extglobOpen = (type, value) => { - const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse.fastpaths(input, options); + } - token.prev = prev; - token.parens = state.parens; - token.output = state.output; - const output = (opts.capture ? '(' : '') + token.open; + if (!parsed.output) { + parsed = parse(input, options); + } - increment('parens'); - push({ type, value, output: state.output ? '' : ONE_CHAR }); - push({ type: 'paren', extglob: true, value: advance(), output }); - extglobs.push(token); - }; + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; - const extglobClose = token => { - let output = token.close + (opts.capture ? ')' : ''); - let rest; +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ - if (token.type === 'negate') { - let extglobStar = star; +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; - if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { - extglobStar = globstar(opts); - } +/** + * Picomatch constants. + * @return {Object} + */ - if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { - output = token.close = `)$))${extglobStar}`; - } +picomatch.constants = constants; - if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { - // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. - // In this case, we need to parse the string and use it in the output of the original pattern. - // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. - // - // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. - const expression = parse(rest, { ...options, fastpaths: false }).output; +/** + * Expose "picomatch" + */ - output = token.close = `)${expression})${extglobStar})`; - } +module.exports = picomatch; - if (token.prev.type === 'bos') { - state.negatedExtglob = true; - } - } - push({ type: 'paren', extglob: true, value, output }); - decrement('parens'); - }; +/***/ }), - /** - * Fast paths - */ +/***/ 1781: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { - let backslashes = false; - let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { - if (first === '\\') { - backslashes = true; - return m; - } - if (first === '?') { - if (esc) { - return esc + first + (rest ? QMARK.repeat(rest.length) : ''); - } - if (index === 0) { - return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); - } - return QMARK.repeat(chars.length); - } - - if (first === '.') { - return DOT_LITERAL.repeat(chars.length); - } - - if (first === '*') { - if (esc) { - return esc + first + (rest ? star : ''); - } - return star; - } - return esc ? m : `\\${m}`; - }); - - if (backslashes === true) { - if (opts.unescape === true) { - output = output.replace(/\\/g, ''); - } else { - output = output.replace(/\\+/g, m => { - return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); - }); - } - } +const utils = __nccwpck_require__(4059); +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = __nccwpck_require__(5595); - if (output === input && opts.contains === true) { - state.output = input; - return state; - } +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; - state.output = utils.wrapOutput(output, state, options); - return state; +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; } +}; - /** - * Tokenize input until we reach end-of-string - */ +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ - while (!eos()) { - value = advance(); +const scan = (input, options) => { + const opts = options || {}; - if (value === '\u0000') { - continue; - } + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; - /** - * Escaped characters - */ + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; - if (value === '\\') { - const next = peek(); + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; - if (next === '/' && opts.bash !== true) { - continue; - } + while (index < length) { + code = advance(); + let next; - if (next === '.' || next === ';') { - continue; - } + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); - if (!next) { - value += '\\'; - push({ type: 'text', value }); - continue; + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; } + continue; + } - // collapse slashes to reduce potential for exploits - const match = /^\\+/.exec(remaining()); - let slashes = 0; + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; - if (match && match[0].length > 2) { - slashes = match[0].length; - state.index += slashes; - if (slashes % 2 !== 0) { - value += '\\'; + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; } - } - if (opts.unescape === true) { - value = advance(); - } else { - value += advance(); - } + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } - if (state.brackets === 0) { - push({ type: 'text', value }); - continue; - } - } + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; - /** - * If we're inside a regex character class, continue - * until we reach the closing bracket. - */ + if (scanToEnd === true) { + continue; + } - if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { - if (opts.posix !== false && value === ':') { - const inner = prev.value.slice(1); - if (inner.includes('[')) { - prev.posix = true; + break; + } - if (inner.includes(':')) { - const idx = prev.value.lastIndexOf('['); - const pre = prev.value.slice(0, idx); - const rest = prev.value.slice(idx + 2); - const posix = POSIX_REGEX_SOURCE[rest]; - if (posix) { - prev.value = pre + posix; - state.backtrack = true; - advance(); + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; - if (!bos.output && tokens.indexOf(prev) === 1) { - bos.output = ONE_CHAR; - } - continue; - } + if (scanToEnd === true) { + continue; } - } - } - if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { - value = `\\${value}`; - } + break; + } - if (value === ']' && (prev.value === '[' || prev.value === '[^')) { - value = `\\${value}`; - } + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; - if (opts.posix === true && value === '!' && prev.value === '[') { - value = '^'; + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } } - prev.value += value; - append({ value }); - continue; - } - - /** - * If we're inside a quoted string, continue - * until we reach the closing double quote. - */ - - if (state.quotes === 1 && value !== '"') { - value = utils.escapeRegex(value); - prev.value += value; - append({ value }); - continue; - } - - /** - * Double quotes - */ - - if (value === '"') { - state.quotes = state.quotes === 1 ? 0 : 1; - if (opts.keepQuotes === true) { - push({ type: 'text', value }); + if (scanToEnd === true) { + continue; } - continue; - } - - /** - * Parentheses - */ - if (value === '(') { - increment('parens'); - push({ type: 'paren', value }); - continue; + break; } - if (value === ')') { - if (state.parens === 0 && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '(')); - } + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; - const extglob = extglobs[extglobs.length - 1]; - if (extglob && state.parens === extglob.parens + 1) { - extglobClose(extglobs.pop()); + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; continue; } - push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); - decrement('parens'); + lastIndex = index + 1; continue; } - /** - * Square brackets - */ + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; - if (value === '[') { - if (opts.nobracket === true || !remaining().includes(']')) { - if (opts.nobracket !== true && opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('closing', ']')); + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; } - value = `\\${value}`; - } else { - increment('brackets'); - } - - push({ type: 'bracket', value }); - continue; - } + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } - if (value === ']') { - if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { - push({ type: 'text', value, output: `\\${value}` }); - continue; + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; } + } - if (state.brackets === 0) { - if (opts.strictBrackets === true) { - throw new SyntaxError(syntaxError('opening', '[')); - } + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; - push({ type: 'text', value, output: `\\${value}` }); + if (scanToEnd === true) { continue; } + break; + } - decrement('brackets'); + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; - const prevValue = prev.value.slice(1); - if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { - value = `/${value}`; + if (scanToEnd === true) { + continue; } + break; + } - prev.value += value; - append({ value }); + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } - // when literal brackets are explicitly disabled - // assume we should match with a regex character class - if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) { - continue; + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } } - const escaped = utils.escapeRegex(prev.value); - state.output = state.output.slice(0, -prev.value.length); - - // when literal brackets are explicitly enabled - // assume we should escape the brackets to match literal characters - if (opts.literalBrackets === true) { - state.output += escaped; - prev.value = escaped; + if (scanToEnd === true) { continue; } - // when the user specifies nothing, try to match both - prev.value = `(${capture}${escaped}|${prev.value})`; - state.output += prev.value; - continue; + break; } - /** - * Braces - */ - - if (value === '{' && opts.nobrace !== true) { - increment('braces'); - - const open = { - type: 'brace', - value, - output: '(', - outputIndex: state.output.length, - tokensIndex: state.tokens.length - }; - - braces.push(open); - push(open); + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; continue; } - if (value === '}') { - const brace = braces[braces.length - 1]; - - if (opts.nobrace === true || !brace) { - push({ type: 'text', value, output: value }); - continue; - } - - let output = ')'; + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; - if (brace.dots === true) { - const arr = tokens.slice(); - const range = []; + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } - for (let i = arr.length - 1; i >= 0; i--) { - tokens.pop(); - if (arr[i].type === 'brace') { + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; break; } - if (arr[i].type !== 'dots') { - range.unshift(arr[i].value); - } - } - - output = expandRange(range, opts); - state.backtrack = true; - } - - if (brace.comma !== true && brace.dots !== true) { - const out = state.output.slice(0, brace.outputIndex); - const toks = state.tokens.slice(brace.tokensIndex); - brace.value = brace.output = '\\{'; - value = output = '\\}'; - state.output = out; - for (const t of toks) { - state.output += (t.output || t.value); } + continue; } - - push({ type: 'brace', value, output }); - decrement('braces'); - braces.pop(); - continue; + break; } - /** - * Pipes - */ + if (isGlob === true) { + finished = true; - if (value === '|') { - if (extglobs.length > 0) { - extglobs[extglobs.length - 1].conditions++; + if (scanToEnd === true) { + continue; } - push({ type: 'text', value }); - continue; + + break; } + } - /** - * Commas - */ + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } - if (value === ',') { - let output = value; + let base = str; + let prefix = ''; + let glob = ''; - const brace = braces[braces.length - 1]; - if (brace && stack[stack.length - 1] === 'braces') { - brace.comma = true; - output = '|'; - } + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } - push({ type: 'comma', value, output }); - continue; + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); } + } - /** - * Slashes - */ + if (opts.unescape === true) { + if (glob) glob = utils.removeBackslashes(glob); - if (value === '/') { - // if the beginning of the glob is "./", advance the start - // to the current index, and don't add the "./" characters - // to the state. This greatly simplifies lookbehinds when - // checking for BOS characters like "!" and "." (not "./") - if (prev.type === 'dot' && state.index === state.start + 1) { - state.start = state.index + 1; - state.consumed = ''; - state.output = ''; - tokens.pop(); - prev = bos; // reset "prev" to the first token - continue; - } - - push({ type: 'slash', value, output: SLASH_LITERAL }); - continue; + if (base && backslashes === true) { + base = utils.removeBackslashes(base); } + } - /** - * Dots - */ - - if (value === '.') { - if (state.braces > 0 && prev.type === 'dot') { - if (prev.value === '.') prev.output = DOT_LITERAL; - const brace = braces[braces.length - 1]; - prev.type = 'dots'; - prev.output += value; - prev.value += value; - brace.dots = true; - continue; - } - - if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { - push({ type: 'text', value, output: DOT_LITERAL }); - continue; - } + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; - push({ type: 'dot', value, output: DOT_LITERAL }); - continue; + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); } + state.tokens = tokens; + } - /** - * Question marks - */ - - if (value === '?') { - const isGroup = prev && prev.value === '('; - if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('qmark', value); - continue; - } - - if (prev && prev.type === 'paren') { - const next = peek(); - let output = value; - - if (next === '<' && !utils.supportsLookbehinds()) { - throw new Error('Node.js v10 or higher is required for regex lookbehinds'); - } + if (opts.parts === true || opts.tokens === true) { + let prevIndex; - if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { - output = `\\${value}`; + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; } - - push({ type: 'text', value, output }); - continue; + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; } - - if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { - push({ type: 'qmark', value, output: QMARK_NO_DOT }); - continue; + if (idx !== 0 || value !== '') { + parts.push(value); } - - push({ type: 'qmark', value, output: QMARK }); - continue; + prevIndex = i; } - /** - * Exclamation - */ - - if (value === '!') { - if (opts.noextglob !== true && peek() === '(') { - if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { - extglobOpen('negate', value); - continue; - } - } + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); - if (opts.nonegate !== true && state.index === 0) { - negate(); - continue; + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; } } - /** - * Plus - */ + state.slashes = slashes; + state.parts = parts; + } - if (value === '+') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - extglobOpen('plus', value); - continue; - } + return state; +}; - if ((prev && prev.value === '(') || opts.regex === false) { - push({ type: 'plus', value, output: PLUS_LITERAL }); - continue; - } +module.exports = scan; - if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { - push({ type: 'plus', value }); - continue; - } - push({ type: 'plus', value: PLUS_LITERAL }); - continue; - } +/***/ }), - /** - * Plain text - */ +/***/ 4059: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (value === '@') { - if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { - push({ type: 'at', extglob: true, value, output: '' }); - continue; - } - push({ type: 'text', value }); - continue; - } - /** - * Plain text - */ +const path = __nccwpck_require__(6928); +const win32 = process.platform === 'win32'; +const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL +} = __nccwpck_require__(5595); - if (value !== '*') { - if (value === '$' || value === '^') { - value = `\\${value}`; - } +exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); +exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); +exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); +exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); +exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); - const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); - if (match) { - value += match[0]; - state.index += match[0].length; - } +exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); +}; - push({ type: 'text', value }); - continue; - } +exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; +}; - /** - * Stars - */ +exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; +}; - if (prev && (prev.type === 'globstar' || prev.star === true)) { - prev.type = 'star'; - prev.star = true; - prev.value += value; - prev.output = star; - state.backtrack = true; - state.globstar = true; - consume(value); - continue; - } +exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; +}; - let rest = remaining(); - if (opts.noextglob !== true && /^\([^?]/.test(rest)) { - extglobOpen('star', value); - continue; - } +exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; +}; - if (prev.type === 'star') { - if (opts.noglobstar === true) { - consume(value); - continue; - } +exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; - const prior = prev.prev; - const before = prior.prev; - const isStart = prior.type === 'slash' || prior.type === 'bos'; - const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; +}; - if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { - push({ type: 'star', value, output: '' }); - continue; - } - const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); - const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); - if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { - push({ type: 'star', value, output: '' }); - continue; - } +/***/ }), - // strip consecutive `/**/` - while (rest.slice(0, 3) === '/**') { - const after = input[state.index + 4]; - if (after && after !== '/') { - break; - } - rest = rest.slice(3); - consume('/**', 3); - } +/***/ 5546: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (prior.type === 'bos' && eos()) { - prev.type = 'globstar'; - prev.value += value; - prev.output = globstar(opts); - state.output = prev.output; - state.globstar = true; - consume(value); - continue; - } +module.exports = __nccwpck_require__(7084); - if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; +/***/ }), - prev.type = 'globstar'; - prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); - prev.value += value; - state.globstar = true; - state.output += prior.output + prev.output; - consume(value); - continue; - } +/***/ 7084: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { - const end = rest[1] !== void 0 ? '|$' : ''; +var RetryOperation = __nccwpck_require__(9538); - state.output = state.output.slice(0, -(prior.output + prev.output).length); - prior.output = `(?:${prior.output}`; +exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); +}; - prev.type = 'globstar'; - prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; - prev.value += value; +exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } - state.output += prior.output + prev.output; - state.globstar = true; + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1000, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } - consume(value + advance()); + if (opts.minTimeout > opts.maxTimeout) { + throw new Error('minTimeout is greater than maxTimeout'); + } - push({ type: 'slash', value: '/', output: '' }); - continue; - } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } - if (prior.type === 'bos' && rest[0] === '/') { - prev.type = 'globstar'; - prev.value += value; - prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; - state.output = prev.output; - state.globstar = true; - consume(value + advance()); - push({ type: 'slash', value: '/', output: '' }); - continue; - } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } - // remove single star from output - state.output = state.output.slice(0, -prev.output.length); + // sort the array numerically ascending + timeouts.sort(function(a,b) { + return a - b; + }); - // reset previous token to globstar - prev.type = 'globstar'; - prev.output = globstar(opts); - prev.value += value; + return timeouts; +}; - // reset output with globstar - state.output += prev.output; - state.globstar = true; - consume(value); - continue; - } +exports.createTimeout = function(attempt, opts) { + var random = (opts.randomize) + ? (Math.random() + 1) + : 1; - const token = { type: 'star', value, output: star }; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); - if (opts.bash === true) { - token.output = '.*?'; - if (prev.type === 'bos' || prev.type === 'slash') { - token.output = nodot + token.output; + return timeout; +}; + +exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === 'function') { + methods.push(key); } - push(token); - continue; } + } - if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { - token.output = value; - push(token); - continue; - } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; - if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { - if (prev.type === 'dot') { - state.output += NO_DOT_SLASH; - prev.output += NO_DOT_SLASH; + obj[method] = function retryWrapper(original) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); - } else if (opts.dot === true) { - state.output += NO_DOTS_SLASH; - prev.output += NO_DOTS_SLASH; + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); - } else { - state.output += nodot; - prev.output += nodot; - } + op.attempt(function() { + original.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } +}; - if (peek() !== '*') { - state.output += ONE_CHAR; - prev.output += ONE_CHAR; - } - } - push(token); - } +/***/ }), - while (state.brackets > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); - state.output = utils.escapeLast(state.output, '['); - decrement('brackets'); - } +/***/ 9538: +/***/ ((module) => { - while (state.parens > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); - state.output = utils.escapeLast(state.output, '('); - decrement('parens'); +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; } - while (state.braces > 0) { - if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); - state.output = utils.escapeLast(state.output, '{'); - decrement('braces'); - } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; - if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { - push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); } +} +module.exports = RetryOperation; - // rebuild the output if we had to backtrack at any point - if (state.backtrack === true) { - state.output = ''; +RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); +} - for (const token of state.tokens) { - state.output += token.output != null ? token.output : token.value; +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } - if (token.suffix) { - state.output += token.suffix; - } - } + this._timeouts = []; + this._cachedTimeouts = null; +}; + +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); } - return state; -}; + if (!err) { + return false; + } + var currentTime = new Date().getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error('RetryOperation timeout occurred')); + return false; + } -/** - * Fast paths for creating regular expressions for common glob patterns. - * This can significantly speed up processing and has very little downside - * impact when none of the fast paths match. - */ + this._errors.push(err); -parse.fastpaths = (input, options) => { - const opts = { ...options }; - const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; - const len = input.length; - if (len > max) { - throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } } - input = REPLACEMENTS[input] || input; - const win32 = utils.isWindows(options); + var self = this; + this._timer = setTimeout(function() { + self._attempts++; - // create constants based on platform, for windows or posix - const { - DOT_LITERAL, - SLASH_LITERAL, - ONE_CHAR, - DOTS_SLASH, - NO_DOT, - NO_DOTS, - NO_DOTS_SLASH, - STAR, - START_ANCHOR - } = constants.globChars(win32); + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); - const nodot = opts.dot ? NO_DOTS : NO_DOT; - const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; - const capture = opts.capture ? '' : '?:'; - const state = { negated: false, prefix: '' }; - let star = opts.bash === true ? '.*?' : STAR; + if (self._options.unref) { + self._timeout.unref(); + } + } - if (opts.capture) { - star = `(${star})`; + self._fn(self._attempts); + }, timeout); + + if (this._options.unref) { + this._timer.unref(); } - const globstar = opts => { - if (opts.noglobstar === true) return star; - return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; - }; + return true; +}; - const create = str => { - switch (str) { - case '*': - return `${nodot}${ONE_CHAR}${star}`; +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; - case '.*': - return `${DOT_LITERAL}${ONE_CHAR}${star}`; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } - case '*.*': - return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } - case '*/*': - return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + this._operationStart = new Date().getTime(); - case '**': - return nodot + globstar(opts); + this._fn(this._attempts); +}; - case '**/*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; - case '**/*.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; - case '**/.*': - return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; +RetryOperation.prototype.start = RetryOperation.prototype.try; - default: { - const match = /^(.*?)\.(\w+)$/.exec(str); - if (!match) return; +RetryOperation.prototype.errors = function() { + return this._errors; +}; - const source = create(match[1]); - if (!source) return; +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; - return source + DOT_LITERAL + match[2]; - } - } - }; +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } - const output = utils.removePrefix(input, state); - let source = create(output); + var counts = {}; + var mainError = null; + var mainErrorCount = 0; - if (source && opts.strictSlashes !== true) { - source += `${SLASH_LITERAL}?`; + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } } - return source; + return mainError; }; -module.exports = parse; - /***/ }), -/***/ 8016: +/***/ 9379: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const path = __nccwpck_require__(6928); -const scan = __nccwpck_require__(1781); -const parse = __nccwpck_require__(8265); -const utils = __nccwpck_require__(4059); -const constants = __nccwpck_require__(5595); -const isObject = val => val && typeof val === 'object' && !Array.isArray(val); - -/** - * Creates a matcher function from one or more glob patterns. The - * returned function takes a string to match as its first argument, - * and returns true if the string is a match. The returned matcher - * function also takes a boolean as the second argument that, when true, - * returns an object with additional information. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch(glob[, options]); - * - * const isMatch = picomatch('*.!(*a)'); - * console.log(isMatch('a.a')); //=> false - * console.log(isMatch('a.b')); //=> true - * ``` - * @name picomatch - * @param {String|Array} `globs` One or more glob patterns. - * @param {Object=} `options` - * @return {Function=} Returns a matcher function. - * @api public - */ - -const picomatch = (glob, options, returnState = false) => { - if (Array.isArray(glob)) { - const fns = glob.map(input => picomatch(input, options, returnState)); - const arrayMatcher = str => { - for (const isMatch of fns) { - const state = isMatch(str); - if (state) return state; - } - return false; - }; - return arrayMatcher; +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY } - const isState = isObject(glob) && glob.tokens && glob.input; + constructor (comp, options) { + options = parseOptions(options) - if (glob === '' || (typeof glob !== 'string' && !isState)) { - throw new TypeError('Expected pattern to be a non-empty string'); - } + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } - const opts = options || {}; - const posix = utils.isWindows(options); - const regex = isState - ? picomatch.compileRe(glob, options) - : picomatch.makeRe(glob, options, false, true); + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) - const state = regex.state; - delete regex.state; + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } - let isIgnored = () => false; - if (opts.ignore) { - const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; - isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + debug('comp', this) } - const matcher = (input, returnObject = false) => { - const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix }); - const result = { glob, state, regex, posix, input, output, match, isMatch }; - - if (typeof opts.onResult === 'function') { - opts.onResult(result); - } + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) - if (isMatch === false) { - result.isMatch = false; - return returnObject ? result : false; + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) } - if (isIgnored(input)) { - if (typeof opts.onIgnore === 'function') { - opts.onIgnore(result); - } - result.isMatch = false; - return returnObject ? result : false; + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' } - if (typeof opts.onMatch === 'function') { - opts.onMatch(result); + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) } - return returnObject ? result : true; - }; + } - if (returnState) { - matcher.state = state; + toString () { + return this.value } - return matcher; -}; + test (version) { + debug('Comparator.test', version, this.options.loose) -/** - * Test `input` with the given `regex`. This is used by the main - * `picomatch()` function to test the input string. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.test(input, regex[, options]); - * - * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); - * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } - * ``` - * @param {String} `input` String to test. - * @param {RegExp} `regex` - * @return {Object} Returns an object with matching info. - * @api public - */ + if (this.semver === ANY || version === ANY) { + return true + } -picomatch.test = (input, regex, options, { glob, posix } = {}) => { - if (typeof input !== 'string') { - throw new TypeError('Expected input to be a string'); - } + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } - if (input === '') { - return { isMatch: false, output: '' }; + return cmp(version, this.operator, this.semver, this.options) } - const opts = options || {}; - const format = opts.format || (posix ? utils.toPosixSlashes : null); - let match = input === glob; - let output = (match && format) ? format(input) : input; - - if (match === false) { - output = format ? format(input) : input; - match = output === glob; - } + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } - if (match === false || opts.capture === true) { - if (opts.matchBase === true || opts.basename === true) { - match = picomatch.matchBase(input, regex, options, posix); - } else { - match = regex.exec(output); + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) } - } - return { isMatch: Boolean(match), match, output }; -}; + options = parseOptions(options) -/** - * Match the basename of a filepath. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.matchBase(input, glob[, options]); - * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true - * ``` - * @param {String} `input` String to test. - * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). - * @return {Boolean} - * @api public - */ + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } -picomatch.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { - const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); - return regex.test(path.basename(input)); -}; + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} -/** - * Returns true if **any** of the given glob `patterns` match the specified `string`. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.isMatch(string, patterns[, options]); - * - * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true - * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false - * ``` - * @param {String|Array} str The string to test. - * @param {String|Array} patterns One or more glob patterns to use for matching. - * @param {Object} [options] See available [options](#options). - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +module.exports = Comparator -picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); +const parseOptions = __nccwpck_require__(356) +const { safeRe: re, t } = __nccwpck_require__(5471) +const cmp = __nccwpck_require__(8646) +const debug = __nccwpck_require__(1159) +const SemVer = __nccwpck_require__(7163) +const Range = __nccwpck_require__(6782) -/** - * Parse a glob pattern to create the source string for a regular - * expression. - * - * ```js - * const picomatch = require('picomatch'); - * const result = picomatch.parse(pattern[, options]); - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Object} Returns an object with useful properties and output to be used as a regex source string. - * @api public - */ -picomatch.parse = (pattern, options) => { - if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); - return parse(pattern, { ...options, fastpaths: false }); -}; +/***/ }), -/** - * Scan a glob pattern to separate the pattern into segments. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.scan(input[, options]); - * - * const result = picomatch.scan('!./foo/*.js'); - * console.log(result); - * { prefix: '!./', - * input: '!./foo/*.js', - * start: 3, - * base: 'foo', - * glob: '*.js', - * isBrace: false, - * isBracket: false, - * isGlob: true, - * isExtglob: false, - * isGlobstar: false, - * negated: true } - * ``` - * @param {String} `input` Glob pattern to scan. - * @param {Object} `options` - * @return {Object} Returns an object with - * @api public - */ +/***/ 6782: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -picomatch.scan = (input, options) => scan(input, options); -/** - * Compile a regular expression from the `state` object returned by the - * [parse()](#parse) method. - * - * @param {Object} `state` - * @param {Object} `options` - * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. - * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. - * @return {RegExp} - * @api public - */ -picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => { - if (returnOutput === true) { - return state.output; - } +const SPACE_CHARACTERS = /\s+/g - const opts = options || {}; - const prepend = opts.contains ? '' : '^'; - const append = opts.contains ? '' : '$'; +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) - let source = `${prepend}(?:${state.output})${append}`; - if (state && state.negated === true) { - source = `^(?!${source}).*$`; - } + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } - const regex = picomatch.toRegex(source, options); - if (returnState === true) { - regex.state = state; - } + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } - return regex; -}; + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -/** - * Create a regular expression from a parsed glob pattern. - * - * ```js - * const picomatch = require('picomatch'); - * const state = picomatch.parse('*.js'); - * // picomatch.compileRe(state[, options]); - * - * console.log(picomatch.compileRe(state)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` - * @param {String} `state` The object returned from the `.parse` method. - * @param {Object} `options` - * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. - * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') -picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { - if (!input || typeof input !== 'string') { - throw new TypeError('Expected a non-empty string'); - } + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) - let parsed = { negated: false, fastpaths: true }; + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } - if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { - parsed.output = parse.fastpaths(input, options); - } + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } - if (!parsed.output) { - parsed = parse(input, options); + this.formatted = undefined } - return picomatch.compileRe(parsed, options, returnOutput, returnState); -}; - -/** - * Create a regular expression from the given regex source string. - * - * ```js - * const picomatch = require('picomatch'); - * // picomatch.toRegex(source[, options]); - * - * const { output } = picomatch.parse('*.js'); - * console.log(picomatch.toRegex(output)); - * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ - * ``` - * @param {String} `source` Regular expression source string. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ - -picomatch.toRegex = (source, options) => { - try { - const opts = options || {}; - return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); - } catch (err) { - if (options && options.debug === true) throw err; - return /$^/; + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted } -}; -/** - * Picomatch constants. - * @return {Object} - */ + format () { + return this.range + } -picomatch.constants = constants; + toString () { + return this.range + } -/** - * Expose "picomatch" - */ + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } -module.exports = picomatch; + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) -/***/ }), + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) -/***/ 1781: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + // At this point, the range is completely trimmed and + // ready to be split into comparators. + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) -const utils = __nccwpck_require__(4059); -const { - CHAR_ASTERISK, /* * */ - CHAR_AT, /* @ */ - CHAR_BACKWARD_SLASH, /* \ */ - CHAR_COMMA, /* , */ - CHAR_DOT, /* . */ - CHAR_EXCLAMATION_MARK, /* ! */ - CHAR_FORWARD_SLASH, /* / */ - CHAR_LEFT_CURLY_BRACE, /* { */ - CHAR_LEFT_PARENTHESES, /* ( */ - CHAR_LEFT_SQUARE_BRACKET, /* [ */ - CHAR_PLUS, /* + */ - CHAR_QUESTION_MARK, /* ? */ - CHAR_RIGHT_CURLY_BRACE, /* } */ - CHAR_RIGHT_PARENTHESES, /* ) */ - CHAR_RIGHT_SQUARE_BRACKET /* ] */ -} = __nccwpck_require__(5595); + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) -const isPathSeparator = code => { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; -}; + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } -const depth = token => { - if (token.isPrefix !== true) { - token.depth = token.isGlobstar ? Infinity : 1; + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result } -}; - -/** - * Quickly scans a glob pattern and returns an object with a handful of - * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), - * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not - * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). - * - * ```js - * const pm = require('picomatch'); - * console.log(pm.scan('foo/bar/*.js')); - * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {Object} Returns an object with tokens and regex source string. - * @api public - */ - -const scan = (input, options) => { - const opts = options || {}; - const length = input.length - 1; - const scanToEnd = opts.parts === true || opts.scanToEnd === true; - const slashes = []; - const tokens = []; - const parts = []; - - let str = input; - let index = -1; - let start = 0; - let lastIndex = 0; - let isBrace = false; - let isBracket = false; - let isGlob = false; - let isExtglob = false; - let isGlobstar = false; - let braceEscaped = false; - let backslashes = false; - let negated = false; - let negatedExtglob = false; - let finished = false; - let braces = 0; - let prev; - let code; - let token = { value: '', depth: 0, isGlob: false }; + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } - const eos = () => index >= length; - const peek = () => str.charCodeAt(index + 1); - const advance = () => { - prev = code; - return str.charCodeAt(++index); - }; + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } - while (index < length) { - code = advance(); - let next; + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } - if (code === CHAR_LEFT_CURLY_BRACE) { - braceEscaped = true; + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } - continue; } + return false + } +} - if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { - braces++; +module.exports = Range - while (eos() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; - } +const LRU = __nccwpck_require__(1383) +const cache = new LRU() - if (code === CHAR_LEFT_CURLY_BRACE) { - braces++; - continue; - } +const parseOptions = __nccwpck_require__(356) +const Comparator = __nccwpck_require__(9379) +const debug = __nccwpck_require__(1159) +const SemVer = __nccwpck_require__(7163) +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __nccwpck_require__(5471) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101) - if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' - if (scanToEnd === true) { - continue; - } +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() - break; - } + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) - if (braceEscaped !== true && code === CHAR_COMMA) { - isBrace = token.isBrace = true; - isGlob = token.isGlob = true; - finished = true; + testComparator = remainingComparators.pop() + } - if (scanToEnd === true) { - continue; - } + return result +} - break; - } +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} - if (code === CHAR_RIGHT_CURLY_BRACE) { - braces--; +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' - if (braces === 0) { - braceEscaped = false; - isBrace = token.isBrace = true; - finished = true; - break; - } - } - } +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} - if (scanToEnd === true) { - continue; - } +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret - break; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` } - if (code === CHAR_FORWARD_SLASH) { - slashes.push(index); - tokens.push(token); - token = { value: '', depth: 0, isGlob: false }; - - if (finished === true) continue; - if (prev === CHAR_DOT && index === (start + 1)) { - start += 2; - continue; - } - - lastIndex = index + 1; - continue; - } + debug('tilde return', ret) + return ret + }) +} - if (opts.noext !== true) { - const isExtglobChar = code === CHAR_PLUS - || code === CHAR_AT - || code === CHAR_ASTERISK - || code === CHAR_QUESTION_MARK - || code === CHAR_EXCLAMATION_MARK; +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} - if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - isExtglob = token.isExtglob = true; - finished = true; - if (code === CHAR_EXCLAMATION_MARK && index === start) { - negatedExtglob = true; - } +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret - if (scanToEnd === true) { - while (eos() !== true && (code = advance())) { - if (code === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } - - if (code === CHAR_RIGHT_PARENTHESES) { - isGlob = token.isGlob = true; - finished = true; - break; - } - } - continue; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` } - break; + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` } } - if (code === CHAR_ASTERISK) { - if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; - isGlob = token.isGlob = true; - finished = true; + debug('caret return', ret) + return ret + }) +} - if (scanToEnd === true) { - continue; - } - break; +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' } - if (code === CHAR_QUESTION_MARK) { - isGlob = token.isGlob = true; - finished = true; + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' - if (scanToEnd === true) { - continue; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' } - break; - } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 - if (code === CHAR_LEFT_SQUARE_BRACKET) { - while (eos() !== true && (next = advance())) { - if (next === CHAR_BACKWARD_SLASH) { - backslashes = token.backslashes = true; - advance(); - continue; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 } - - if (next === CHAR_RIGHT_SQUARE_BRACKET) { - isBracket = token.isBracket = true; - isGlob = token.isGlob = true; - finished = true; - break; + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 } } - if (scanToEnd === true) { - continue; + if (gtlt === '<') { + pr = '-0' } - break; - } - - if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { - negated = token.negated = true; - start++; - continue; + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` } - if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { - isGlob = token.isGlob = true; - - if (scanToEnd === true) { - while (eos() !== true && (code = advance())) { - if (code === CHAR_LEFT_PARENTHESES) { - backslashes = token.backslashes = true; - code = advance(); - continue; - } + debug('xRange return', ret) - if (code === CHAR_RIGHT_PARENTHESES) { - finished = true; - break; - } - } - continue; - } - break; - } + return ret + }) +} - if (isGlob === true) { - finished = true; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} - if (scanToEnd === true) { - continue; - } +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} - break; - } +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` } - if (opts.noext === true) { - isExtglob = false; - isGlob = false; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` } - let base = str; - let prefix = ''; - let glob = ''; + return `${from} ${to}`.trim() +} - if (start > 0) { - prefix = str.slice(0, start); - str = str.slice(start); - lastIndex -= start; +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } } - if (base && isGlob === true && lastIndex > 0) { - base = str.slice(0, lastIndex); - glob = str.slice(lastIndex); - } else if (isGlob === true) { - base = ''; - glob = str; - } else { - base = str; - } + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } - if (base && base !== '' && base !== '/' && base !== str) { - if (isPathSeparator(base.charCodeAt(base.length - 1))) { - base = base.slice(0, -1); + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } } + + // Version has a -pre, but it's not one of the ones we like. + return false } - if (opts.unescape === true) { - if (glob) glob = utils.removeBackslashes(glob); + return true +} - if (base && backslashes === true) { - base = utils.removeBackslashes(base); - } - } - const state = { - prefix, - input, - start, - base, - glob, - isBrace, - isBracket, - isGlob, - isExtglob, - isGlobstar, - negated, - negatedExtglob - }; +/***/ }), - if (opts.tokens === true) { - state.maxDepth = 0; - if (!isPathSeparator(code)) { - tokens.push(token); - } - state.tokens = tokens; - } +/***/ 7163: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (opts.parts === true || opts.tokens === true) { - let prevIndex; - for (let idx = 0; idx < slashes.length; idx++) { - const n = prevIndex ? prevIndex + 1 : start; - const i = slashes[idx]; - const value = input.slice(n, i); - if (opts.tokens) { - if (idx === 0 && start !== 0) { - tokens[idx].isPrefix = true; - tokens[idx].value = prefix; - } else { - tokens[idx].value = value; - } - depth(tokens[idx]); - state.maxDepth += tokens[idx].depth; - } - if (idx !== 0 || value !== '') { - parts.push(value); - } - prevIndex = i; - } - if (prevIndex && prevIndex + 1 < input.length) { - const value = input.slice(prevIndex + 1); - parts.push(value); +const debug = __nccwpck_require__(1159) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101) +const { safeRe: re, t } = __nccwpck_require__(5471) - if (opts.tokens) { - tokens[tokens.length - 1].value = value; - depth(tokens[tokens.length - 1]); - state.maxDepth += tokens[tokens.length - 1].depth; +const parseOptions = __nccwpck_require__(356) +const { compareIdentifiers } = __nccwpck_require__(3348) +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) } - state.slashes = slashes; - state.parts = parts; - } - - return state; -}; + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } -module.exports = scan; + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) -/***/ }), + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } -/***/ 4059: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this.raw = version + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -const path = __nccwpck_require__(6928); -const win32 = process.platform === 'win32'; -const { - REGEX_BACKSLASH, - REGEX_REMOVE_BACKSLASH, - REGEX_SPECIAL_CHARS, - REGEX_SPECIAL_CHARS_GLOBAL -} = __nccwpck_require__(5595); + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } -exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); -exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); -exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); -exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); -exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } -exports.removeBackslashes = str => { - return str.replace(REGEX_REMOVE_BACKSLASH, match => { - return match === '\\' ? '' : match; - }); -}; + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } -exports.supportsLookbehinds = () => { - const segs = process.version.slice(1).split('.').map(Number); - if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { - return true; + this.build = m[5] ? m[5].split('.') : [] + this.format() } - return false; -}; -exports.isWindows = options => { - if (options && typeof options.windows === 'boolean') { - return options.windows; + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version } - return win32 === true || path.sep === '\\'; -}; - -exports.escapeLast = (input, char, lastIdx) => { - const idx = input.lastIndexOf(char, lastIdx); - if (idx === -1) return input; - if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); - return `${input.slice(0, idx)}\\${input.slice(idx)}`; -}; -exports.removePrefix = (input, state = {}) => { - let output = input; - if (output.startsWith('./')) { - output = output.slice(2); - state.prefix = './'; + toString () { + return this.version } - return output; -}; -exports.wrapOutput = (input, state = {}, options = {}) => { - const prepend = options.contains ? '' : '^'; - const append = options.contains ? '' : '$'; + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } - let output = `${prepend}(?:${input})${append}`; - if (state.negated === true) { - output = `(?:^(?!${output}).*$)`; + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) } - return output; -}; + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -/***/ }), + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } -/***/ 5546: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -module.exports = __nccwpck_require__(7084); + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } -/***/ }), + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } -/***/ 7084: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -var RetryOperation = __nccwpck_require__(9538); + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this } +} - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } +module.exports = SemVer - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); - } - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); +/***/ }), - return timeouts; -}; +/***/ 1799: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - return timeout; -}; +const parse = __nccwpck_require__(6353) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } - } +/***/ }), - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; +/***/ 8646: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; +const eq = __nccwpck_require__(5082) +const neq = __nccwpck_require__(4974) +const gt = __nccwpck_require__(6599) +const gte = __nccwpck_require__(1236) +const lt = __nccwpck_require__(3872) +const lte = __nccwpck_require__(6717) +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b -/***/ }), + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b -/***/ 9538: -/***/ ((module) => { + case '': + case '=': + case '==': + return eq(a, b, loose) -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } + case '!=': + return neq(a, b, loose) - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; + case '>': + return gt(a, b, loose) - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) } } -module.exports = RetryOperation; +module.exports = cmp -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); -} -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } +/***/ }), - this._timeouts = []; - this._cachedTimeouts = null; -}; +/***/ 5385: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); + + +const SemVer = __nccwpck_require__(7163) +const parse = __nccwpck_require__(6353) +const { safeRe: re, t } = __nccwpck_require__(5471) + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version } - if (!err) { - return false; + if (typeof version === 'number') { + version = String(version) } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; + + if (typeof version !== 'string') { + return null } - this._errors.push(err); + options = options || {} - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 } - var self = this; - this._timer = setTimeout(function() { - self._attempts++; + if (match === null) { + return null + } - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' - if (self._options.unref) { - self._timeout.unref(); - } - } + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce - self._fn(self._attempts); - }, timeout); - if (this._options.unref) { - this._timer.unref(); - } +/***/ }), - return true; -}; +/***/ 7648: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } +const SemVer = __nccwpck_require__(7163) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild - this._operationStart = new Date().getTime(); - this._fn(this._attempts); -}; +/***/ }), -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; +/***/ 6874: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; -RetryOperation.prototype.start = RetryOperation.prototype.try; -RetryOperation.prototype.errors = function() { - return this._errors; -}; +const compare = __nccwpck_require__(8469) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } +/***/ }), - var counts = {}; - var mainError = null; - var mainErrorCount = 0; +/***/ 8469: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - counts[message] = count; - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } - } +const SemVer = __nccwpck_require__(7163) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) - return mainError; -}; +module.exports = compare /***/ }), -/***/ 9379: +/***/ 711: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY +const parse = __nccwpck_require__(6353) + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null } - constructor (comp, options) { - options = parseOptions(options) + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' } + return 'patch' } + } - comp = comp.trim().split(/\s+/).join(' ') - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } + if (v1.major !== v2.major) { + return prefix + 'major' + } - debug('comp', this) + if (v1.minor !== v2.minor) { + return prefix + 'minor' } - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } + // high and low are preleases + return 'prerelease' +} - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } +module.exports = diff - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } - } - toString () { - return this.value - } +/***/ }), - test (version) { - debug('Comparator.test', version, this.options.loose) +/***/ 5082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.semver === ANY || version === ANY) { - return true - } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - return cmp(version, this.operator, this.semver, this.options) - } +const compare = __nccwpck_require__(8469) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } +/***/ }), - options = parseOptions(options) +/***/ 6599: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Special cases where nothing can possibly be lower - if (options.includePrerelease && - (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { - return false - } - if (!options.includePrerelease && - (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { - return false - } - // Same direction increasing (> or >=) - if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { - return true - } - // Same direction decreasing (< or <=) - if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { - return true - } - // same SemVer and both sides are inclusive (<= or >=) - if ( - (this.semver.version === comp.semver.version) && - this.operator.includes('=') && comp.operator.includes('=')) { - return true - } - // opposite directions less than - if (cmp(this.semver, '<', comp.semver, options) && - this.operator.startsWith('>') && comp.operator.startsWith('<')) { - return true - } - // opposite directions greater than - if (cmp(this.semver, '>', comp.semver, options) && - this.operator.startsWith('<') && comp.operator.startsWith('>')) { - return true - } - return false - } -} -module.exports = Comparator +const compare = __nccwpck_require__(8469) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt + + +/***/ }), + +/***/ 1236: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8469) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte + + +/***/ }), + +/***/ 2338: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + -const parseOptions = __nccwpck_require__(356) -const { safeRe: re, t } = __nccwpck_require__(5471) -const cmp = __nccwpck_require__(8646) -const debug = __nccwpck_require__(1159) const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc /***/ }), -/***/ 6782: +/***/ 3872: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const SPACE_CHARACTERS = /\s+/g +const compare = __nccwpck_require__(8469) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - options = parseOptions(options) - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } - } +/***/ }), - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.formatted = undefined - return this - } +/***/ 6717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - // First reduce all whitespace as much as possible so we do not have to rely - // on potentially slow regexes like \s*. This is then stored and used for - // future error messages as well. - this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') - // First, split on || - this.set = this.raw - .split('||') - // map the range to a 2d array of comparators - .map(r => this.parseRange(r.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) +const compare = __nccwpck_require__(8469) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`) - } - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0] - this.set = this.set.filter(c => !isNullSet(c[0])) - if (this.set.length === 0) { - this.set = [first] - } else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c] - break - } - } - } - } +/***/ }), - this.formatted = undefined - } +/***/ 8511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get range () { - if (this.formatted === undefined) { - this.formatted = '' - for (let i = 0; i < this.set.length; i++) { - if (i > 0) { - this.formatted += '||' - } - const comps = this.set[i] - for (let k = 0; k < comps.length; k++) { - if (k > 0) { - this.formatted += ' ' - } - this.formatted += comps[k].toString().trim() - } - } - } - return this.formatted - } - format () { - return this.range - } - toString () { - return this.range - } +const SemVer = __nccwpck_require__(7163) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major - parseRange (range) { - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = - (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | - (this.options.loose && FLAG_LOOSE) - const memoKey = memoOpts + ':' + range - const cached = cache.get(memoKey) - if (cached) { - return cached - } - const loose = this.options.loose - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) - debug('hyphen replace', range) +/***/ }), - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range) +/***/ 2603: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - debug('tilde trim', range) - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - debug('caret trim', range) - // At this point, the range is completely trimmed and - // ready to be split into comparators. +const SemVer = __nccwpck_require__(7163) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor - let rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - if (loose) { - // in loose mode, throw out any that are not valid comparators - rangeList = rangeList.filter(comp => { - debug('loose invalid filter', comp, this.options) - return !!comp.match(re[t.COMPARATORLOOSE]) - }) - } - debug('range list', rangeList) +/***/ }), - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - const rangeMap = new Map() - const comparators = rangeList.map(comp => new Comparator(comp, this.options)) - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp] - } - rangeMap.set(comp.value, comp) - } - if (rangeMap.size > 1 && rangeMap.has('')) { - rangeMap.delete('') - } +/***/ 4974: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const result = [...rangeMap.values()] - cache.set(memoKey, result) - return result - } - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } +const compare = __nccwpck_require__(8469) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } +/***/ }), - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } +/***/ 6353: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(7163) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null } - return false + throw er } } -module.exports = Range +module.exports = parse + + +/***/ }), + +/***/ 8756: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + -const LRU = __nccwpck_require__(1383) -const cache = new LRU() -const parseOptions = __nccwpck_require__(356) -const Comparator = __nccwpck_require__(9379) -const debug = __nccwpck_require__(1159) const SemVer = __nccwpck_require__(7163) -const { - safeRe: re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace, -} = __nccwpck_require__(5471) -const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(5101) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch -const isNullSet = c => c.value === '<0.0.0-0' -const isAny = c => c.value === '' -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() +/***/ }), - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) +/***/ 5714: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - testComparator = remainingComparators.pop() - } - return result -} -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp +const parse = __nccwpck_require__(6353) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null } +module.exports = prerelease -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 -// ~0.0.1 --> >=0.0.1 <0.1.0-0 -const replaceTildes = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceTilde(c, options)) - .join(' ') -} -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret +/***/ }), - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0` - } +/***/ 2173: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - debug('tilde return', ret) - return ret - }) -} -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 -// ^1.2.3 --> >=1.2.3 <2.0.0-0 -// ^1.2.0 --> >=1.2.0 <2.0.0-0 -// ^0.0.1 --> >=0.0.1 <0.0.2-0 -// ^0.1.0 --> >=0.1.0 <0.2.0-0 -const replaceCarets = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceCaret(c, options)) - .join(' ') -} -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - const z = options.includePrerelease ? '-0' : '' - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret +const compare = __nccwpck_require__(8469) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0` - } - } - debug('caret return', ret) - return ret - }) -} +/***/ }), -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp - .split(/\s+/) - .map((c) => replaceXRange(c, options)) - .join(' ') -} +/***/ 7192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp - if (gtlt === '=' && anyX) { - gtlt = '' - } - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' +const compareBuild = __nccwpck_require__(7648) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } +/***/ }), - if (gtlt === '<') { - pr = '-0' - } +/***/ 8011: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0` - } - debug('xRange return', ret) - return ret - }) +const Range = __nccwpck_require__(6782) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) } +module.exports = satisfies -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp - .trim() - .replace(re[t.STAR], '') -} -const replaceGTE0 = (comp, options) => { - debug('replaceGTE0', comp, options) - return comp - .trim() - .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') -} +/***/ }), -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 -// TODO build? -const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` - } else if (fpr) { - from = `>=${from}` - } else { - from = `>=${from}${incPr ? '-0' : ''}` - } +/***/ 9872: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0` - } else { - to = `<=${to}` - } - return `${from} ${to}`.trim() -} -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } +const compareBuild = __nccwpck_require__(7648) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } +/***/ }), - // Version has a -pre, but it's not one of the ones we like. - return false - } +/***/ 8780: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return true + + +const parse = __nccwpck_require__(6353) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null } +module.exports = valid /***/ }), -/***/ 7163: +/***/ 2088: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const debug = __nccwpck_require__(1159) -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(5101) -const { safeRe: re, t } = __nccwpck_require__(5471) - -const parseOptions = __nccwpck_require__(356) -const { compareIdentifiers } = __nccwpck_require__(3348) -class SemVer { - constructor (version, options) { - options = parseOptions(options) +// just pre-load all the stuff that index.js lazily exports +const internalRe = __nccwpck_require__(5471) +const constants = __nccwpck_require__(5101) +const SemVer = __nccwpck_require__(7163) +const identifiers = __nccwpck_require__(3348) +const parse = __nccwpck_require__(6353) +const valid = __nccwpck_require__(8780) +const clean = __nccwpck_require__(1799) +const inc = __nccwpck_require__(2338) +const diff = __nccwpck_require__(711) +const major = __nccwpck_require__(8511) +const minor = __nccwpck_require__(2603) +const patch = __nccwpck_require__(8756) +const prerelease = __nccwpck_require__(5714) +const compare = __nccwpck_require__(8469) +const rcompare = __nccwpck_require__(2173) +const compareLoose = __nccwpck_require__(6874) +const compareBuild = __nccwpck_require__(7648) +const sort = __nccwpck_require__(9872) +const rsort = __nccwpck_require__(7192) +const gt = __nccwpck_require__(6599) +const lt = __nccwpck_require__(3872) +const eq = __nccwpck_require__(5082) +const neq = __nccwpck_require__(4974) +const gte = __nccwpck_require__(1236) +const lte = __nccwpck_require__(6717) +const cmp = __nccwpck_require__(8646) +const coerce = __nccwpck_require__(5385) +const Comparator = __nccwpck_require__(9379) +const Range = __nccwpck_require__(6782) +const satisfies = __nccwpck_require__(8011) +const toComparators = __nccwpck_require__(4750) +const maxSatisfying = __nccwpck_require__(5574) +const minSatisfying = __nccwpck_require__(8595) +const minVersion = __nccwpck_require__(1866) +const validRange = __nccwpck_require__(4737) +const outside = __nccwpck_require__(280) +const gtr = __nccwpck_require__(2276) +const ltr = __nccwpck_require__(5213) +const intersects = __nccwpck_require__(3465) +const simplifyRange = __nccwpck_require__(2028) +const subset = __nccwpck_require__(1489) +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) - } - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } +/***/ }), - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease +/***/ 5101: +/***/ ((module) => { - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - this.raw = version +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} - this.build = m[5] ? m[5].split('.') : [] - this.format() - } - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version - } +/***/ }), - toString () { - return this.version - } +/***/ 1159: +/***/ ((module) => { - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer(other, this.options) - } - if (other.version === this.version) { - return 0 - } - return this.compareMain(other) || this.comparePre(other) - } +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +module.exports = debug - return ( - compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) - ) - } - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +/***/ }), - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } +/***/ 3348: +/***/ ((module) => { - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('build compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier, identifierBase) { - if (release.startsWith('pre')) { - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } - // Avoid an invalid semver results - if (identifier) { - const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) - if (!match || match[1] !== identifier) { - throw new Error(`invalid identifier: ${identifier}`) - } - } - } + if (anum && bnum) { + a = +a + b = +b + } - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier, identifierBase) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier, identifierBase) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier, identifierBase) - this.inc('pre', identifier, identifierBase) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier, identifierBase) - } - this.inc('pre', identifier, identifierBase) - break - case 'release': - if (this.prerelease.length === 0) { - throw new Error(`version ${this.raw} is not a prerelease`) - } - this.prerelease.length = 0 - break + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': { - const base = Number(identifierBase) ? 1 : 0 +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) - if (this.prerelease.length === 0) { - this.prerelease = [base] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - if (identifier === this.prerelease.join('.') && identifierBase === false) { - throw new Error('invalid increment argument: identifier already exists') - } - this.prerelease.push(base) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - let prerelease = [identifier, base] - if (identifierBase === false) { - prerelease = [identifier] - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease - } - } else { - this.prerelease = prerelease - } - } - break - } - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.raw = this.format() - if (this.build.length) { - this.raw += `+${this.build.join('.')}` - } - return this - } +module.exports = { + compareIdentifiers, + rcompareIdentifiers, } -module.exports = SemVer - /***/ }), -/***/ 1799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - +/***/ 1383: +/***/ ((module) => { -const parse = __nccwpck_require__(6353) -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } -/***/ }), + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value + } + } -/***/ 8646: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + delete (key) { + return this.map.delete(key) + } + set (key, value) { + const deleted = this.delete(key) + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } -const eq = __nccwpck_require__(5082) -const neq = __nccwpck_require__(4974) -const gt = __nccwpck_require__(6599) -const gte = __nccwpck_require__(1236) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(6717) + this.map.set(key, value) + } -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a === b + return this + } +} - case '!==': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a !== b +module.exports = LRUCache - case '': - case '=': - case '==': - return eq(a, b, loose) - case '!=': - return neq(a, b, loose) +/***/ }), - case '>': - return gt(a, b, loose) +/***/ 356: +/***/ ((module) => { - case '>=': - return gte(a, b, loose) - case '<': - return lt(a, b, loose) - case '<=': - return lte(a, b, loose) +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } - default: - throw new TypeError(`Invalid operator: ${op}`) + if (typeof options !== 'object') { + return looseOption } + + return options } -module.exports = cmp +module.exports = parseOptions /***/ }), -/***/ 5385: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - +/***/ 5471: +/***/ ((module, exports, __nccwpck_require__) => { -const SemVer = __nccwpck_require__(7163) -const parse = __nccwpck_require__(6353) -const { safeRe: re, t } = __nccwpck_require__(5471) -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } - if (typeof version === 'number') { - version = String(version) - } +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = __nccwpck_require__(5101) +const debug = __nccwpck_require__(1159) +exports = module.exports = {} - if (typeof version !== 'string') { - return null - } +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const safeSrc = exports.safeSrc = [] +const t = exports.t = {} +let R = 0 - options = options || {} +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' - let match = null - if (!options.rtl) { - match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] - let next - while ((next = coerceRtlRegex.exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - coerceRtlRegex.lastIndex = -1 - } +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] - if (match === null) { - return null +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) } - - const major = match[2] - const minor = match[3] || '0' - const patch = match[4] || '0' - const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' - const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' - - return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) + return value } -module.exports = coerce - -/***/ }), +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + safeSrc[index] = safe + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} -/***/ 7648: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') -const SemVer = __nccwpck_require__(7163) -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -module.exports = compareBuild +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) -/***/ }), +// ## Main Version +// Three dot-separated numeric identifiers. -/***/ 6874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. -const compare = __nccwpck_require__(8469) -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) -/***/ }), +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. -/***/ 8469: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. -const SemVer = __nccwpck_require__(7163) -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) -module.exports = compare +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) -/***/ }), +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. -/***/ 711: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) +createToken('FULL', `^${src[t.FULLPLAIN]}$`) -const parse = __nccwpck_require__(6353) - -const diff = (version1, version2) => { - const v1 = parse(version1, null, true) - const v2 = parse(version2, null, true) - const comparison = v1.compare(v2) - - if (comparison === 0) { - return null - } - - const v1Higher = comparison > 0 - const highVersion = v1Higher ? v1 : v2 - const lowVersion = v1Higher ? v2 : v1 - const highHasPre = !!highVersion.prerelease.length - const lowHasPre = !!lowVersion.prerelease.length - - if (lowHasPre && !highHasPre) { - // Going from prerelease -> no prerelease requires some special casing - - // If the low version has only a major, then it will always be a major - // Some examples: - // 1.0.0-1 -> 1.0.0 - // 1.0.0-1 -> 1.1.1 - // 1.0.0-1 -> 2.0.0 - if (!lowVersion.patch && !lowVersion.minor) { - return 'major' - } - - // If the main part has no difference - if (lowVersion.compareMain(highVersion) === 0) { - if (lowVersion.minor && !lowVersion.patch) { - return 'minor' - } - return 'patch' - } - } +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) - // add the `pre` prefix if we are going to a prerelease version - const prefix = highHasPre ? 'pre' : '' +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) - if (v1.major !== v2.major) { - return prefix + 'major' - } +createToken('GTLT', '((?:<|>)?=?)') - if (v1.minor !== v2.minor) { - return prefix + 'minor' - } +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) - if (v1.patch !== v2.patch) { - return prefix + 'patch' - } +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) - // high and low are preleases - return 'prerelease' -} +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) -module.exports = diff +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) -/***/ }), +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') -/***/ 5082: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') -const compare = __nccwpck_require__(8469) -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) -/***/ }), +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) -/***/ 6599: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) -const compare = __nccwpck_require__(8469) -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') /***/ }), -/***/ 1236: +/***/ 2276: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const compare = __nccwpck_require__(8469) -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte +// Determine if version is greater than all the versions possible in the range. +const outside = __nccwpck_require__(280) +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr /***/ }), -/***/ 2338: +/***/ 3465: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const SemVer = __nccwpck_require__(7163) - -const inc = (version, release, options, identifier, identifierBase) => { - if (typeof (options) === 'string') { - identifierBase = identifier - identifier = options - options = undefined - } - - try { - return new SemVer( - version instanceof SemVer ? version.version : version, - options - ).inc(release, identifier, identifierBase).version - } catch (er) { - return null - } +const Range = __nccwpck_require__(6782) +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) } -module.exports = inc - - -/***/ }), - -/***/ 3872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt - - -/***/ }), - -/***/ 6717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8469) -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte +module.exports = intersects /***/ }), -/***/ 8511: +/***/ 5213: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const SemVer = __nccwpck_require__(7163) -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major +const outside = __nccwpck_require__(280) +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr /***/ }), -/***/ 2603: +/***/ 5574: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(7163) -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor - - -/***/ }), - -/***/ 4974: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - +const Range = __nccwpck_require__(6782) -const compare = __nccwpck_require__(8469) -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying /***/ }), -/***/ 6353: +/***/ 8595: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(7163) -const parse = (version, options, throwErrors = false) => { - if (version instanceof SemVer) { - return version - } +const Range = __nccwpck_require__(6782) +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null try { - return new SemVer(version, options) + rangeObj = new Range(range, options) } catch (er) { - if (!throwErrors) { - return null - } - throw er + return null } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min } - -module.exports = parse +module.exports = minSatisfying /***/ }), -/***/ 8756: +/***/ 1866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const SemVer = __nccwpck_require__(7163) -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch +const Range = __nccwpck_require__(6782) +const gt = __nccwpck_require__(6599) + +const minVersion = (range, loose) => { + range = new Range(range, loose) + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } -/***/ }), + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } -/***/ 5714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + if (minver && range.test(minver)) { + return minver + } -const parse = __nccwpck_require__(6353) -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + return null } -module.exports = prerelease +module.exports = minVersion /***/ }), -/***/ 2173: +/***/ 280: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const compare = __nccwpck_require__(8469) -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare - - -/***/ }), - -/***/ 7192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +const SemVer = __nccwpck_require__(7163) +const Comparator = __nccwpck_require__(9379) +const { ANY } = Comparator +const Range = __nccwpck_require__(6782) +const satisfies = __nccwpck_require__(8011) +const gt = __nccwpck_require__(6599) +const lt = __nccwpck_require__(3872) +const lte = __nccwpck_require__(6717) +const gte = __nccwpck_require__(1236) +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } -const compareBuild = __nccwpck_require__(7648) -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. -/***/ }), + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] -/***/ 8011: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let high = null + let low = null + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } -const Range = __nccwpck_require__(6782) -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } } - return range.test(version) + return true } -module.exports = satisfies - - -/***/ }), - -/***/ 9872: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const compareBuild = __nccwpck_require__(7648) -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort +module.exports = outside /***/ }), -/***/ 8780: +/***/ 2028: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const parse = __nccwpck_require__(6353) -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __nccwpck_require__(8011) +const compare = __nccwpck_require__(8469) +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range } -module.exports = valid /***/ }), -/***/ 2088: +/***/ 1489: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// just pre-load all the stuff that index.js lazily exports -const internalRe = __nccwpck_require__(5471) -const constants = __nccwpck_require__(5101) -const SemVer = __nccwpck_require__(7163) -const identifiers = __nccwpck_require__(3348) -const parse = __nccwpck_require__(6353) -const valid = __nccwpck_require__(8780) -const clean = __nccwpck_require__(1799) -const inc = __nccwpck_require__(2338) -const diff = __nccwpck_require__(711) -const major = __nccwpck_require__(8511) -const minor = __nccwpck_require__(2603) -const patch = __nccwpck_require__(8756) -const prerelease = __nccwpck_require__(5714) -const compare = __nccwpck_require__(8469) -const rcompare = __nccwpck_require__(2173) -const compareLoose = __nccwpck_require__(6874) -const compareBuild = __nccwpck_require__(7648) -const sort = __nccwpck_require__(9872) -const rsort = __nccwpck_require__(7192) -const gt = __nccwpck_require__(6599) -const lt = __nccwpck_require__(3872) -const eq = __nccwpck_require__(5082) -const neq = __nccwpck_require__(4974) -const gte = __nccwpck_require__(1236) -const lte = __nccwpck_require__(6717) -const cmp = __nccwpck_require__(8646) -const coerce = __nccwpck_require__(5385) -const Comparator = __nccwpck_require__(9379) const Range = __nccwpck_require__(6782) +const Comparator = __nccwpck_require__(9379) +const { ANY } = Comparator const satisfies = __nccwpck_require__(8011) -const toComparators = __nccwpck_require__(4750) -const maxSatisfying = __nccwpck_require__(5574) -const minSatisfying = __nccwpck_require__(8595) -const minVersion = __nccwpck_require__(1866) -const validRange = __nccwpck_require__(4737) -const outside = __nccwpck_require__(280) -const gtr = __nccwpck_require__(2276) -const ltr = __nccwpck_require__(5213) -const intersects = __nccwpck_require__(3465) -const simplifyRange = __nccwpck_require__(2028) -const subset = __nccwpck_require__(1489) -module.exports = { - parse, - valid, - clean, - inc, - diff, - major, - minor, - patch, - prerelease, - compare, - rcompare, - compareLoose, - compareBuild, - sort, - rsort, - gt, - lt, - eq, - neq, - gte, - lte, - cmp, - coerce, - Comparator, - Range, - satisfies, - toComparators, - maxSatisfying, - minSatisfying, - minVersion, - validRange, - outside, - gtr, - ltr, - intersects, - simplifyRange, - subset, - SemVer, - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - RELEASE_TYPES: constants.RELEASE_TYPES, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, -} - - -/***/ }), - -/***/ 5101: -/***/ ((module) => { - - +const compare = __nccwpck_require__(8469) -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -const SEMVER_SPEC_VERSION = '2.0.0' +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true -const MAX_LENGTH = 256 -const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || -/* istanbul ignore next */ 9007199254740991 +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } -// Max safe segment length for coercion. -const MAX_SAFE_COMPONENT_LENGTH = 16 + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false -// Max safe length for a build identifier. The max length minus 6 characters for -// the shortest version with a build 0.0.0+BUILD. -const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} -const RELEASE_TYPES = [ - 'major', - 'premajor', - 'minor', - 'preminor', - 'patch', - 'prepatch', - 'prerelease', -] +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] -module.exports = { - MAX_LENGTH, - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_SAFE_INTEGER, - RELEASE_TYPES, - SEMVER_SPEC_VERSION, - FLAG_INCLUDE_PRERELEASE: 0b001, - FLAG_LOOSE: 0b010, -} +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } -/***/ }), + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } -/***/ 1159: -/***/ ((module) => { + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + if (eqSet.size > 1) { + return null + } + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } -const debug = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) -) ? (...args) => console.error('SEMVER', ...args) - : () => {} + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } -module.exports = debug + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } -/***/ }), + return true + } -/***/ 3348: -/***/ ((module) => { + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } -const numeric = /^[0-9]+$/ -const compareIdentifiers = (a, b) => { - const anum = numeric.test(a) - const bnum = numeric.test(b) + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } - if (anum && bnum) { - a = +a - b = +b + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 + return true } -const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} -module.exports = { - compareIdentifiers, - rcompareIdentifiers, +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a } +module.exports = subset + /***/ }), -/***/ 1383: -/***/ ((module) => { +/***/ 4750: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -class LRUCache { - constructor () { - this.max = 1000 - this.map = new Map() - } +const Range = __nccwpck_require__(6782) - get (key) { - const value = this.map.get(key) - if (value === undefined) { - return undefined - } else { - // Remove the key from the map and add it to the end - this.map.delete(key) - this.map.set(key, value) - return value - } - } +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) - delete (key) { - return this.map.delete(key) - } +module.exports = toComparators - set (key, value) { - const deleted = this.delete(key) - if (!deleted && value !== undefined) { - // If cache is full, delete the least recently used item - if (this.map.size >= this.max) { - const firstKey = this.map.keys().next().value - this.delete(firstKey) - } +/***/ }), - this.map.set(key, value) - } +/***/ 4737: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this + + +const Range = __nccwpck_require__(6782) +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null } } - -module.exports = LRUCache +module.exports = validRange /***/ }), -/***/ 356: -/***/ ((module) => { +/***/ 7551: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ -// parse out just the options we care about -const looseOption = Object.freeze({ loose: true }) -const emptyOpts = Object.freeze({ }) -const parseOptions = options => { - if (!options) { - return emptyOpts +const isNumber = __nccwpck_require__(3102); + +const toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); } - if (typeof options !== 'object') { - return looseOption + if (max === void 0 || min === max) { + return String(min); } - return options -} -module.exports = parseOptions + if (isNumber(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } -/***/ }), + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; -/***/ 5471: -/***/ ((module, exports, __nccwpck_require__) => { + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + let a = Math.min(min, max); + let b = Math.max(min, max); + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } -const { - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_LENGTH, -} = __nccwpck_require__(5101) -const debug = __nccwpck_require__(1159) -exports = module.exports = {} + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; -// The actual regexps go on exports.re -const re = exports.re = [] -const safeRe = exports.safeRe = [] -const src = exports.src = [] -const safeSrc = exports.safeSrc = [] -const t = exports.t = {} -let R = 0 + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } -const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } -// Replace some greedy regex tokens to prevent regex dos issues. These regex are -// used internally via the safeRe object since all inputs in this library get -// normalized first to trim and collapse all extra whitespace. The original -// regexes are exported for userland consumption and lower level usage. A -// future breaking change could export the safer regex only with a note that -// all input should have extra whitespace removed. -const safeRegexReplacements = [ - ['\\s', 1], - ['\\d', MAX_LENGTH], - [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], -] - -const makeSafeRegex = (value) => { - for (const [token, max] of safeRegexReplacements) { - value = value - .split(`${token}*`).join(`${token}{0,${max}}`) - .split(`${token}+`).join(`${token}{1,${max}}`) + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); } - return value -} - -const createToken = (name, value, isGlobal) => { - const safe = makeSafeRegex(value) - const index = R++ - debug(name, index, value) - t[name] = index - src[index] = value - safeSrc[index] = safe - re[index] = new RegExp(value, isGlobal ? 'g' : undefined) - safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) -} - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives, opts); -createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') -createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + toRegexRange.cache[cacheKey] = state; + return state.result; +}; -createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + let intersected = filterPatterns(neg, pos, '-?', true, options) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} -// ## Main Version -// Three dot-separated numeric identifiers. +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; -createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`) + let stop = countNines(min, nines); + let stops = new Set([max]); -createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. -// Non-numberic identifiers include numberic identifiers but can be longer. -// Therefore non-numberic identifiers must go first. + stop = countZeros(max + 1, zeros) - 1; -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] -}|${src[t.NUMERICIDENTIFIER]})`) + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] -}|${src[t.NUMERICIDENTIFIERLOOSE]})`) + stops = [...stops]; + stops.sort(compare); + return stops; +} -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ -createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } -createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; -createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + if (startDigit === stopDigit) { + pattern += startDigit; -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit, options); -createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + } else { + count++; + } + } -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. + return { pattern, count: [count], digits }; +} -createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`) +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; -createToken('FULL', `^${src[t.FULLPLAIN]}$`) + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`) + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } -createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } -createToken('GTLT', '((?:<|>)?=?)') + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) -createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } -createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`) + return tokens; +} -createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`) +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; -createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) -createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + for (let ele of arr) { + let { string } = ele; -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -createToken('COERCEPLAIN', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) -createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) -createToken('COERCEFULL', src[t.COERCEPLAIN] + - `(?:${src[t.PRERELEASE]})?` + - `(?:${src[t.BUILD]})?` + - `(?:$|[^\\d])`) -createToken('COERCERTL', src[t.COERCE], true) -createToken('COERCERTLFULL', src[t.COERCEFULL], true) + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } -// Tilde ranges. -// Meaning is "reasonably at or greater than" -createToken('LONETILDE', '(?:~>?)') + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} -createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) -exports.tildeTrimReplace = '$1~' +/** + * Zip strings + */ -createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) -createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} -// Caret ranges. -// Meaning is "at least and backwards compatible with" -createToken('LONECARET', '(?:\\^)') +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} -createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) -exports.caretTrimReplace = '$1^' +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} -createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) -createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} -// A simple gt/lt/eq thing, or just "" to indicate "any version" -createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) -createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) -exports.comparatorTrimReplace = '$1$2$3' +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`) +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} -createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`) +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} -// Star ranges basically just allow anything at all. -createToken('STAR', '(<|>)?=?\\s*\\*') -// >=0.0.0 is like a star -createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') -createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; -/***/ }), + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} -/***/ 2276: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Cache + */ +toRegexRange.cache = {}; +toRegexRange.clearCache = () => (toRegexRange.cache = {}); +/** + * Expose `toRegexRange` + */ -// Determine if version is greater than all the versions possible in the range. -const outside = __nccwpck_require__(280) -const gtr = (version, range, options) => outside(version, range, '>', options) -module.exports = gtr +module.exports = toRegexRange; /***/ }), -/***/ 3465: +/***/ 770: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const Range = __nccwpck_require__(6782) -const intersects = (r1, r2, options) => { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2, options) -} -module.exports = intersects +module.exports = __nccwpck_require__(218); /***/ }), -/***/ 5213: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const outside = __nccwpck_require__(280) -// Determine if version is less than all the versions possible in the range -const ltr = (version, range, options) => outside(version, range, '<', options) -module.exports = ltr +/***/ 218: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/***/ }), -/***/ 5574: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; } -module.exports = maxSatisfying +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} -/***/ }), +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} -/***/ 8595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) -const minSatisfying = (versions, range, options) => { - let min = null - let minSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; } } - }) - return min + socket.destroy(); + self.removeSocket(socket); + }); } -module.exports = minSatisfying - - -/***/ }), +util.inherits(TunnelingAgent, events.EventEmitter); -/***/ 1866: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); -const SemVer = __nccwpck_require__(7163) -const Range = __nccwpck_require__(6782) -const gt = __nccwpck_require__(6599) + function onFree() { + self.emit('free', socket, options); + } -const minVersion = (range, loose) => { - range = new Range(range, loose) + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; - let minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - let setMin = null - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt(compver, setMin)) { - setMin = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }) - if (setMin && (!minver || gt(minver, setMin))) { - minver = setMin + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; } - - if (minver && range.test(minver)) { - return minver + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); } - return null -} -module.exports = minVersion - - -/***/ }), + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); -/***/ 280: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); -const SemVer = __nccwpck_require__(7163) -const Comparator = __nccwpck_require__(9379) -const { ANY } = Comparator -const Range = __nccwpck_require__(6782) -const satisfies = __nccwpck_require__(8011) -const gt = __nccwpck_require__(6599) -const lt = __nccwpck_require__(3872) -const lte = __nccwpck_require__(6717) -const gte = __nccwpck_require__(1236) + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } -const outside = (version, range, hilo, options) => { - version = new SemVer(version, options) - range = new Range(range, options) + function onError(cause) { + connectReq.removeAllListeners(); - let gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); } +}; - // If it satisfies the range it is not outside - if (satisfies(version, range, options)) { - return false +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; } + this.sockets.splice(pos, 1); - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; - let high = null - let low = null +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; } - return true + return host; // for v0.11 or later } -module.exports = outside - - -/***/ }), - -/***/ 2028: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// given a set of versions and a range, create a "simplified" range -// that includes the same versions that the original range does -// If the original range is shorter than the simplified one, return that. -const satisfies = __nccwpck_require__(8011) -const compare = __nccwpck_require__(8469) -module.exports = (versions, range, options) => { - const set = [] - let first = null - let prev = null - const v = versions.sort((a, b) => compare(a, b, options)) - for (const version of v) { - const included = satisfies(version, range, options) - if (included) { - prev = version - if (!first) { - first = version - } - } else { - if (prev) { - set.push([first, prev]) +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } } - prev = null - first = null } } - if (first) { - set.push([first, null]) - } + return target; +} - const ranges = [] - for (const [min, max] of set) { - if (min === max) { - ranges.push(min) - } else if (!max && min === v[0]) { - ranges.push('*') - } else if (!max) { - ranges.push(`>=${min}`) - } else if (min === v[0]) { - ranges.push(`<=${max}`) + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; } else { - ranges.push(`${min} - ${max}`) + args.unshift('TUNNEL:'); } + console.error.apply(console, args); } - const simplified = ranges.join(' || ') - const original = typeof range.raw === 'string' ? range.raw : String(range) - return simplified.length < original.length ? simplified : range +} else { + debug = function() {}; } +exports.debug = debug; // for test /***/ }), -/***/ 1489: +/***/ 6752: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Range = __nccwpck_require__(6782) -const Comparator = __nccwpck_require__(9379) -const { ANY } = Comparator -const satisfies = __nccwpck_require__(8011) -const compare = __nccwpck_require__(8469) +const Client = __nccwpck_require__(6197) +const Dispatcher = __nccwpck_require__(992) +const errors = __nccwpck_require__(8707) +const Pool = __nccwpck_require__(5076) +const BalancedPool = __nccwpck_require__(1093) +const Agent = __nccwpck_require__(9965) +const util = __nccwpck_require__(3440) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(6615) +const buildConnector = __nccwpck_require__(9136) +const MockClient = __nccwpck_require__(7365) +const MockAgent = __nccwpck_require__(7501) +const MockPool = __nccwpck_require__(4004) +const mockErrors = __nccwpck_require__(2429) +const ProxyAgent = __nccwpck_require__(2720) +const RetryHandler = __nccwpck_require__(3573) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) +const DecoratorHandler = __nccwpck_require__(8840) +const RedirectHandler = __nccwpck_require__(8299) +const createRedirectInterceptor = __nccwpck_require__(4415) -// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: -// - Every simple range `r1, r2, ...` is a null set, OR -// - Every simple range `r1, r2, ...` which is not a null set is a subset of -// some `R1, R2, ...` -// -// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: -// - If c is only the ANY comparator -// - If C is only the ANY comparator, return true -// - Else if in prerelease mode, return false -// - else replace c with `[>=0.0.0]` -// - If C is only the ANY comparator -// - if in prerelease mode, return true -// - else replace C with `[>=0.0.0]` -// - Let EQ be the set of = comparators in c -// - If EQ is more than one, return true (null set) -// - Let GT be the highest > or >= comparator in c -// - Let LT be the lowest < or <= comparator in c -// - If GT and LT, and GT.semver > LT.semver, return true (null set) -// - If any C is a = range, and GT or LT are set, return false -// - If EQ -// - If GT, and EQ does not satisfy GT, return true (null set) -// - If LT, and EQ does not satisfy LT, return true (null set) -// - If EQ satisfies every C, return true -// - Else return false -// - If GT -// - If GT.semver is lower than any > or >= comp in C, return false -// - If GT is >=, and GT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the GT.semver tuple, return false -// - If LT -// - If LT.semver is greater than any < or <= comp in C, return false -// - If LT is <=, and LT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the LT.semver tuple, return false -// - Else return true +let hasCrypto +try { + __nccwpck_require__(6982) + hasCrypto = true +} catch { + hasCrypto = false +} -const subset = (sub, dom, options = {}) => { - if (sub === dom) { - return true - } +Object.assign(Dispatcher.prototype, api) - sub = new Range(sub, options) - dom = new Range(dom, options) - let sawNonNull = false +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.RetryHandler = RetryHandler - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options) - sawNonNull = sawNonNull || isSub !== null - if (isSub) { - continue OUTER - } - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) { - return false - } - } - return true -} +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor -const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] -const minimumVersion = [new Comparator('>=0.0.0')] +module.exports.buildConnector = buildConnector +module.exports.errors = errors -const simpleSubset = (sub, dom, options) => { - if (sub === dom) { - return true - } +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) { - return true - } else if (options.includePrerelease) { - sub = minimumVersionWithPreRelease - } else { - sub = minimumVersion + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') } - } - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) { - return true - } else { - dom = minimumVersion + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - } - const eqSet = new Set() - let gt, lt - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') { - gt = higherGT(gt, c, options) - } else if (c.operator === '<' || c.operator === '<=') { - lt = lowerLT(lt, c, options) + 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 { - eqSet.add(c.semver) + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) } - } - if (eqSet.size > 1) { - return null - } + const { agent, dispatcher = getGlobalDispatcher() } = opts - let gtltComp - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options) - if (gtltComp > 0) { - return null - } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { - return null + 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) } +} - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) { - return null - } +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher - if (lt && !satisfies(eq, String(lt), options)) { - return null +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = (__nccwpck_require__(2315).fetch) } - for (const c of dom) { - if (!satisfies(eq, String(c), options)) { - return false + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) } - } - return true + throw err + } } + module.exports.Headers = __nccwpck_require__(6349).Headers + module.exports.Response = __nccwpck_require__(8676).Response + module.exports.Request = __nccwpck_require__(5194).Request + module.exports.FormData = __nccwpck_require__(3073).FormData + module.exports.File = __nccwpck_require__(3041).File + module.exports.FileReader = __nccwpck_require__(2160).FileReader - let higher, lower - let hasDomLT, hasDomGT - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false - } + const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628) - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options) - if (higher === c && higher !== gt) { - return false - } - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { - return false - } - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options) - if (lower === c && lower !== lt) { - return false - } - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { - return false - } - } - if (!c.operator && (lt || gt) && gtltComp !== 0) { - return false - } - } + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) { - return false - } + const { CacheStorage } = __nccwpck_require__(4738) + const { kConstruct } = __nccwpck_require__(296) - if (lt && hasDomGT && !gt && gtltComp !== 0) { - return false - } + // 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) +} - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) { - return false - } +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168) - return true -} + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie -// >=1.2.3 is lower than >1.2.3 -const higherGT = (a, b, options) => { - if (!a) { - return b - } - const comp = compare(a.semver, b.semver, options) - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a -} + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) -// <=1.2.3 is higher than <1.2.3 -const lowerLT = (a, b, options) => { - if (!a) { - return b - } - const comp = compare(a.semver, b.semver, options) - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType } -module.exports = subset - +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(5171) -/***/ }), + module.exports.WebSocket = WebSocket +} -/***/ 4750: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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 -const Range = __nccwpck_require__(6782) +/***/ }), -// Mostly just for testing and legacy API reasons -const toComparators = (range, options) => - new Range(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) +/***/ 9965: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = toComparators -/***/ }), +const { InvalidArgumentError } = __nccwpck_require__(8707) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) +const DispatcherBase = __nccwpck_require__(1) +const Pool = __nccwpck_require__(5076) +const Client = __nccwpck_require__(6197) +const util = __nccwpck_require__(3440) +const createRedirectInterceptor = __nccwpck_require__(4415) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)() -/***/ 4737: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +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() -const Range = __nccwpck_require__(6782) -const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -module.exports = validRange + 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') + } -/***/ 7551: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } -/*! - * to-regex-range - * - * Copyright (c) 2015-present, Jon Schlinkert. - * Released under the MIT License. - */ + 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 -const isNumber = __nccwpck_require__(3102); + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } -const toRegexRange = (min, max, options) => { - if (isNumber(min) === false) { - throw new TypeError('toRegexRange: expected the first argument to be a number'); - } + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } - if (max === void 0 || min === max) { - return String(min); - } + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } - if (isNumber(max) === false) { - throw new TypeError('toRegexRange: expected the second argument to be a number.'); + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } } - let opts = { relaxZeros: true, ...options }; - if (typeof opts.strictZeros === 'boolean') { - opts.relaxZeros = opts.strictZeros === false; + 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 } - let relax = String(opts.relaxZeros); - let shorthand = String(opts.shorthand); - let capture = String(opts.capture); - let wrap = String(opts.wrap); - let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + [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.') + } - if (toRegexRange.cache.hasOwnProperty(cacheKey)) { - return toRegexRange.cache[cacheKey].result; - } + const ref = this[kClients].get(key) - let a = Math.min(min, max); - let b = Math.max(min, max); + 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]) - if (Math.abs(a - b) === 1) { - let result = min + '|' + max; - if (opts.capture) { - return `(${result})`; - } - if (opts.wrap === false) { - return result; + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) } - return `(?:${result})`; - } - - let isPadded = hasPadding(min) || hasPadding(max); - let state = { min, max, a, b }; - let positives = []; - let negatives = []; - if (isPadded) { - state.isPadded = isPadded; - state.maxLen = String(state.max).length; + return dispatcher.dispatch(opts, handler) } - if (a < 0) { - let newMin = b < 0 ? Math.abs(b) : 1; - negatives = splitToPatterns(newMin, Math.abs(a), state, opts); - a = state.a = 0; - } + 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()) + } + } - if (b >= 0) { - positives = splitToPatterns(a, b, state, opts); + await Promise.all(closePromises) } - state.negatives = negatives; - state.positives = positives; - state.result = collatePatterns(negatives, positives, opts); + 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)) + } + } - if (opts.capture === true) { - state.result = `(${state.result})`; - } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { - state.result = `(?:${state.result})`; + await Promise.all(destroyPromises) } +} - toRegexRange.cache[cacheKey] = state; - return state.result; -}; +module.exports = Agent -function collatePatterns(neg, pos, options) { - let onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; - let onlyPositive = filterPatterns(pos, neg, '', false, options) || []; - let intersected = filterPatterns(neg, pos, '-?', true, options) || []; - let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); - return subpatterns.join('|'); -} -function splitToRanges(min, max) { - let nines = 1; - let zeros = 1; +/***/ }), - let stop = countNines(min, nines); - let stops = new Set([max]); +/***/ 158: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (min <= stop && stop <= max) { - stops.add(stop); - nines += 1; - stop = countNines(min, nines); - } +const { addAbortListener } = __nccwpck_require__(3440) +const { RequestAbortedError } = __nccwpck_require__(8707) - stop = countZeros(max + 1, zeros) - 1; +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') - while (min < stop && stop <= max) { - stops.add(stop); - zeros += 1; - stop = countZeros(max + 1, zeros) - 1; +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) } - - stops = [...stops]; - stops.sort(compare); - return stops; } -/** - * Convert a range to a regex pattern - * @param {Number} `start` - * @param {Number} `stop` - * @return {String} - */ +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null -function rangeToPattern(start, stop, options) { - if (start === stop) { - return { pattern: start, count: [], digits: 0 }; + if (!signal) { + return } - let zipped = zip(start, stop); - let digits = zipped.length; - let pattern = ''; - let count = 0; - - for (let i = 0; i < digits; i++) { - let [startDigit, stopDigit] = zipped[i]; + if (signal.aborted) { + abort(self) + return + } - if (startDigit === stopDigit) { - pattern += startDigit; + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } - } else if (startDigit !== '0' || stopDigit !== '9') { - pattern += toCharacterClass(startDigit, stopDigit, options); + addAbortListener(self[kSignal], self[kListener]) +} - } else { - count++; - } +function removeSignal (self) { + if (!self[kSignal]) { + return } - if (count) { - pattern += options.shorthand === true ? '\\d' : '[0-9]'; + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) } - return { pattern, count: [count], digits }; + self[kSignal] = null + self[kListener] = null } -function splitToPatterns(min, max, tok, options) { - let ranges = splitToRanges(min, max); - let tokens = []; - let start = min; - let prev; +module.exports = { + addSignal, + removeSignal +} - for (let i = 0; i < ranges.length; i++) { - let max = ranges[i]; - let obj = rangeToPattern(String(start), String(max), options); - let zeros = ''; - if (!tok.isPadded && prev && prev.pattern === obj.pattern) { - if (prev.count.length > 1) { - prev.count.pop(); - } +/***/ }), - prev.count.push(obj.count[0]); - prev.string = prev.pattern + toQuantifier(prev.count); - start = max + 1; - continue; +/***/ 4660: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { AsyncResource } = __nccwpck_require__(290) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { addSignal, removeSignal } = __nccwpck_require__(158) + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - if (tok.isPadded) { - zeros = padZeros(max, tok, options); + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - obj.string = zeros + obj.pattern + toQuantifier(obj.count); - tokens.push(obj); - start = max + 1; - prev = obj; - } + const { signal, opaque, responseHeaders } = opts - return tokens; -} + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } -function filterPatterns(arr, comparison, prefix, intersection, options) { - let result = []; + super('UNDICI_CONNECT') - for (let ele of arr) { - let { string } = ele; + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null - // only push if _both_ are negative... - if (!intersection && !contains(comparison, 'string', string)) { - result.push(prefix + string); - } + addSignal(this, signal) + } - // or _both_ are positive - if (intersection && contains(comparison, 'string', string)) { - result.push(prefix + string); + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() } + + this.abort = abort + this.context = context } - return result; -} -/** - * Zip strings - */ + onHeaders () { + throw new SocketError('bad connect', null) + } -function zip(a, b) { - let arr = []; - for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); - return arr; -} + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this -function compare(a, b) { - return a > b ? 1 : b > a ? -1 : 0; -} + removeSignal(this) -function contains(arr, key, val) { - return arr.some(ele => ele[key] === val); -} - -function countNines(min, len) { - return Number(String(min).slice(0, -len) + '9'.repeat(len)); -} + this.callback = null -function countZeros(integer, zeros) { - return integer - (integer % Math.pow(10, zeros)); -} + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } -function toQuantifier(digits) { - let [start = 0, stop = ''] = digits; - if (stop || start > 1) { - return `{${start + (stop ? ',' + stop : '')}}`; + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) } - return ''; -} -function toCharacterClass(a, b, options) { - return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; -} + onError (err) { + const { callback, opaque } = this -function hasPadding(str) { - return /^-?(0+)\d/.test(str); -} + removeSignal(this) -function padZeros(value, tok, options) { - if (!tok.isPadded) { - return value; + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } } +} - let diff = Math.abs(tok.maxLen - String(value).length); - let relax = options.relaxZeros !== false; +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } - switch (diff) { - case 0: - return ''; - case 1: - return relax ? '0?' : '0'; - case 2: - return relax ? '0{0,2}' : '00'; - default: { - return relax ? `0{0,${diff}}` : `0{${diff}}`; + 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 })) } } -/** - * Cache - */ - -toRegexRange.cache = {}; -toRegexRange.clearCache = () => (toRegexRange.cache = {}); - -/** - * Expose `toRegexRange` - */ - -module.exports = toRegexRange; +module.exports = connect /***/ }), -/***/ 1552: +/***/ 6862: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var punycode = __nccwpck_require__(4876); -var mappingTable = __nccwpck_require__(2472); +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2203) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) +const assert = __nccwpck_require__(2613) -var PROCESSING_OPTIONS = { - TRANSITIONAL: 0, - NONTRANSITIONAL: 1 -}; +const kResume = Symbol('resume') -function normalize(str) { // fix bug in v8 - return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); -} +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) -function findStatus(val) { - var start = 0; - var end = mappingTable.length - 1; + this[kResume] = null + } - while (start <= end) { - var mid = Math.floor((start + end) / 2); + _read () { + const { [kResume]: resume } = this - 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; + if (resume) { + this[kResume] = null + resume() } } - return null; + _destroy (err, callback) { + this._read() + + callback(err) + } } -var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; +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() + } -function countSymbols(string) { - return string - // replace every surrogate pair with a BMP symbol - .replace(regexAstralSymbols, '_') - // then get the length - .length; + callback(err) + } } -function mapChars(domain_name, useSTD3, processing_option) { - var hasError = false; - var processed = ""; +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') + } - var len = countSymbols(domain_name); - for (var i = 0; i < len; ++i) { - var codePoint = domain_name.codePointAt(i); - var status = findStatus(codePoint); + const { signal, method, opaque, onInfo, responseHeaders } = opts - 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); + 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() } - break; - case "valid": - processed += String.fromCodePoint(codePoint); - break; - case "disallowed_STD3_mapped": - if (useSTD3) { - hasError = true; - processed += String.fromCodePoint(codePoint); + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() } else { - processed += String.fromCodePoint.apply(String, status[2]); + req[kResume] = callback } - break; - case "disallowed_STD3_valid": - if (useSTD3) { - hasError = true; + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() } - processed += String.fromCodePoint(codePoint); - break; - } - } + if (abort && err) { + abort() + } - return { - string: processed, - error: hasError - }; -} + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) -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]/; + removeSignal(this) -function validateLabel(label, processing_option) { - if (label.substr(0, 4) === "xn--") { - label = punycode.toUnicode(label); - processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; - } + callback(err) + } + }).on('prefinish', () => { + const { req } = this - var error = false; + // Node < 15 does not call _final in same tick. + req.push(null) + }) - if (normalize(label) !== label || - (label[3] === "-" && label[4] === "-") || - label[0] === "-" || label[label.length - 1] === "-" || - label.indexOf(".") !== -1 || - label.search(combiningMarksRegex) === 0) { - error = true; - } + this.res = null - 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; - } + addSignal(this, signal) } - return { - label: label, - error: error - }; -} + onConnect (abort, context) { + const { ret, res } = this -function processing(domain_name, useSTD3, processing_option) { - var result = mapChars(domain_name, useSTD3, processing_option); - result.string = normalize(result.string); + assert(!res, 'pipeline cannot be retried') - 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; + if (ret.destroyed) { + throw new RequestAbortedError() } - } - - 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; - } - }); + this.abort = abort + this.context = context + } - if (verifyDnsLength) { - var total = labels.slice(0, labels.length - 1).join(".").length; - if (total.length > 253 || total.length === 0) { - result.error = true; - } + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this - for (var i=0; i < labels.length; ++i) { - if (labels.length > 63 || labels.length === 0) { - result.error = true; - break; + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) } + return } - } - if (result.error) return null; - return labels.join("."); -}; + this.res = new PipelineResponse(resume) -module.exports.toUnicode = function(domain_name, useSTD3) { - var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + 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 + } - return { - domain: result.string, - error: result.error - }; -}; + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } -module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; + 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 -/***/ 770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ret.push(null) + }) + .on('close', () => { + const { ret } = this -module.exports = __nccwpck_require__(218); + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + this.body = body + } -/***/ }), + onData (chunk) { + const { res } = this + return res.push(chunk) + } -/***/ 218: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + 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) + } +} -var net = __nccwpck_require__(9278); -var tls = __nccwpck_require__(4756); -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var events = __nccwpck_require__(4434); -var assert = __nccwpck_require__(2613); -var util = __nccwpck_require__(9023); +module.exports = pipeline -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; +/***/ }), +/***/ 4043: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} +const Readable = __nccwpck_require__(9927) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} +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 -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } - function onFree() { - self.emit('free', socket, options); + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err } - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); + 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) + }) } - }); -}; -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); + addSignal(this, signal) + } - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); + + this.abort = abort + this.context = context } - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; + 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 + }) + } } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); } - function onError(cause) { - connectReq.removeAllListeners(); - - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); + onData (chunk) { + const { res } = this + return res.push(chunk) } -}; -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); + onComplete (trailers) { + const { res } = this - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); + removeSignal(this) + + util.parseHeaders(trailers, this.trailers) + + res.push(null) } -}; -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); + onError (err) { + const { res, callback, body, opaque } = this - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} + removeSignal(this) + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } + if (body) { + this.body = null + util.destroy(body, err) } } - return target; } +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err } - console.error.apply(console, args); + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) } -} else { - debug = function() {}; } -exports.debug = debug; // for test + +module.exports = request +module.exports.RequestHandler = RequestHandler /***/ }), -/***/ 6752: +/***/ 3560: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Client = __nccwpck_require__(6197) -const Dispatcher = __nccwpck_require__(992) -const errors = __nccwpck_require__(8707) -const Pool = __nccwpck_require__(5076) -const BalancedPool = __nccwpck_require__(1093) -const Agent = __nccwpck_require__(9965) +const { finished, PassThrough } = __nccwpck_require__(2203) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8707) const util = __nccwpck_require__(3440) -const { InvalidArgumentError } = errors -const api = __nccwpck_require__(6615) -const buildConnector = __nccwpck_require__(9136) -const MockClient = __nccwpck_require__(7365) -const MockAgent = __nccwpck_require__(7501) -const MockPool = __nccwpck_require__(4004) -const mockErrors = __nccwpck_require__(2429) -const ProxyAgent = __nccwpck_require__(2720) -const RetryHandler = __nccwpck_require__(3573) -const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) -const DecoratorHandler = __nccwpck_require__(8840) -const RedirectHandler = __nccwpck_require__(8299) -const createRedirectInterceptor = __nccwpck_require__(4415) - -let hasCrypto -try { - __nccwpck_require__(6982) - hasCrypto = true -} catch { - hasCrypto = false -} - -Object.assign(Dispatcher.prototype, api) - -module.exports.Dispatcher = Dispatcher -module.exports.Client = Client -module.exports.Pool = Pool -module.exports.BalancedPool = BalancedPool -module.exports.Agent = Agent -module.exports.ProxyAgent = ProxyAgent -module.exports.RetryHandler = RetryHandler - -module.exports.DecoratorHandler = DecoratorHandler -module.exports.RedirectHandler = RedirectHandler -module.exports.createRedirectInterceptor = createRedirectInterceptor - -module.exports.buildConnector = buildConnector -module.exports.errors = errors +const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) -function makeDispatcher (fn) { - return (url, opts, handler) => { - if (typeof opts === 'function') { - handler = opts - opts = null +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { - throw new InvalidArgumentError('invalid url') - } + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts - if (opts != null && typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - if (opts && opts.path != null) { - if (typeof opts.path !== 'string') { - throw new InvalidArgumentError('invalid opts.path') + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') } - let path = opts.path - if (!opts.path.startsWith('/')) { - path = `/${path}` + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - url = new URL(util.parseOrigin(url).origin + path) - } else { - if (!opts) { - opts = typeof url === 'object' ? url : {} + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') } - url = util.parseURL(url) + 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 } - const { agent, dispatcher = getGlobalDispatcher() } = opts + 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 (agent) { - throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) } - 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) + addSignal(this, signal) } -} - -module.exports.setGlobalDispatcher = setGlobalDispatcher -module.exports.getGlobalDispatcher = getGlobalDispatcher -if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { - let fetchImpl = null - module.exports.fetch = async function fetch (resource) { - if (!fetchImpl) { - fetchImpl = (__nccwpck_require__(2315).fetch) + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() } - try { - return await fetchImpl(...arguments) - } catch (err) { - if (typeof err === 'object') { - Error.captureStackTrace(err, this) - } - - throw err - } + this.abort = abort + this.context = context } - module.exports.Headers = __nccwpck_require__(6349).Headers - module.exports.Response = __nccwpck_require__(8676).Response - module.exports.Request = __nccwpck_require__(5194).Request - module.exports.FormData = __nccwpck_require__(3073).FormData - module.exports.File = __nccwpck_require__(3041).File - module.exports.FileReader = __nccwpck_require__(2160).FileReader - - const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628) - module.exports.setGlobalOrigin = setGlobalOrigin - module.exports.getGlobalOrigin = getGlobalOrigin + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this - const { CacheStorage } = __nccwpck_require__(4738) - const { kConstruct } = __nccwpck_require__(296) + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - // 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 (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } -if (util.nodeMajor >= 16) { - const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168) + this.factory = null - module.exports.deleteCookie = deleteCookie - module.exports.getCookies = getCookies - module.exports.getSetCookies = getSetCookies - module.exports.setCookie = setCookie + let res - const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() - module.exports.parseMIMEType = parseMIMEType - module.exports.serializeAMimeType = serializeAMimeType -} + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } -if (util.nodeMajor >= 18 && hasCrypto) { - const { WebSocket } = __nccwpck_require__(5171) + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) - module.exports.WebSocket = WebSocket -} + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } -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) + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this -module.exports.MockClient = MockClient -module.exports.MockPool = MockPool -module.exports.MockAgent = MockAgent -module.exports.mockErrors = mockErrors + 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() + } + }) + } -/***/ 9965: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + res.on('drain', resume) + this.res = res + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) -const DispatcherBase = __nccwpck_require__(1) -const Pool = __nccwpck_require__(5076) -const Client = __nccwpck_require__(6197) -const util = __nccwpck_require__(3440) -const createRedirectInterceptor = __nccwpck_require__(4415) -const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)() + return needDrain !== true + } -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') + onData (chunk) { + const { res } = this -function defaultFactory (origin, opts) { - return opts && opts.connections === 1 - ? new Client(origin, opts) - : new Pool(origin, opts) -} + return res ? res.write(chunk) : true + } -class Agent extends DispatcherBase { - constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { - super() + onComplete (trailers) { + const { res } = this - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } + removeSignal(this) - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') + if (!res) { + return } - if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } + this.trailers = util.parseHeaders(trailers) - if (connect && typeof connect !== 'function') { - connect = { ...connect } - } + res.end() + } - this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) - ? options.interceptors.Agent - : [createRedirectInterceptor({ maxRedirections })] + onError (err) { + const { res, callback, opaque, body } = this - 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) - } - }) + removeSignal(this) - const agent = this + this.factory = null - this[kOnDrain] = (origin, targets) => { - agent.emit('drain', origin, [agent, ...targets]) + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) } - this[kOnConnect] = (origin, targets) => { - agent.emit('connect', origin, [agent, ...targets]) + if (body) { + this.body = null + util.destroy(body, err) } + } +} - 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) +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) + }) + }) } - 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)) - } + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err } - - await Promise.all(destroyPromises) - } -} - -module.exports = Agent - - -/***/ }), - -/***/ 158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { addAbortListener } = __nccwpck_require__(3440) -const { RequestAbortedError } = __nccwpck_require__(8707) - -const kListener = Symbol('kListener') -const kSignal = Symbol('kSignal') - -function abort (self) { - if (self.abort) { - self.abort() - } else { - self.onError(new RequestAbortedError()) - } -} - -function addSignal (self, signal) { - self[kSignal] = null - self[kListener] = null - - if (!signal) { - return - } - - if (signal.aborted) { - abort(self) - return - } - - self[kSignal] = signal - self[kListener] = () => { - abort(self) - } - - addAbortListener(self[kSignal], self[kListener]) -} - -function removeSignal (self) { - if (!self[kSignal]) { - return - } - - if ('removeEventListener' in self[kSignal]) { - self[kSignal].removeEventListener('abort', self[kListener]) - } else { - self[kSignal].removeListener('abort', self[kListener]) + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) } - - self[kSignal] = null - self[kListener] = null } -module.exports = { - addSignal, - removeSignal -} +module.exports = stream /***/ }), -/***/ 4660: +/***/ 1882: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { AsyncResource } = __nccwpck_require__(290) const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) +const { AsyncResource } = __nccwpck_require__(290) const util = __nccwpck_require__(3440) const { addSignal, removeSignal } = __nccwpck_require__(158) +const assert = __nccwpck_require__(2613) -class ConnectHandler extends AsyncResource { +class UpgradeHandler extends AsyncResource { constructor (opts, callback) { if (!opts || typeof opts !== 'object') { throw new InvalidArgumentError('invalid opts') @@ -36889,12 +33963,13 @@ class ConnectHandler extends AsyncResource { throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') } - super('UNDICI_CONNECT') + super('UNDICI_UPGRADE') - this.opaque = opaque || null this.responseHeaders = responseHeaders || null + this.opaque = opaque || null this.callback = callback this.abort = null + this.context = null addSignal(this, signal) } @@ -36905,28 +33980,23 @@ class ConnectHandler extends AsyncResource { } this.abort = abort - this.context = context + this.context = null } onHeaders () { - throw new SocketError('bad connect', null) + throw new SocketError('bad upgrade', null) } onUpgrade (statusCode, rawHeaders, socket) { const { callback, opaque, context } = this + assert.strictEqual(statusCode, 101) + 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) - } - + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) this.runInAsyncScope(callback, null, null, { - statusCode, headers, socket, opaque, @@ -36948,18 +34018,22 @@ class ConnectHandler extends AsyncResource { } } -function connect (opts, callback) { +function upgrade (opts, callback) { if (callback === undefined) { return new Promise((resolve, reject) => { - connect.call(this, opts, (err, data) => { + upgrade.call(this, opts, (err, data) => { return err ? reject(err) : resolve(data) }) }) } try { - const connectHandler = new ConnectHandler(opts, callback) - this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + 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 @@ -36969,16589 +34043,15807 @@ function connect (opts, callback) { } } -module.exports = connect +module.exports = upgrade /***/ }), -/***/ 6862: +/***/ 6615: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { - Readable, - Duplex, - PassThrough -} = __nccwpck_require__(2203) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) -const assert = __nccwpck_require__(2613) +module.exports.request = __nccwpck_require__(4043) +module.exports.stream = __nccwpck_require__(3560) +module.exports.pipeline = __nccwpck_require__(6862) +module.exports.upgrade = __nccwpck_require__(1882) +module.exports.connect = __nccwpck_require__(4660) -const kResume = Symbol('resume') -class PipelineRequest extends Readable { - constructor () { - super({ autoDestroy: true }) +/***/ }), - this[kResume] = null - } +/***/ 9927: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _read () { - const { [kResume]: resume } = this +// Ported from https://github.com/nodejs/undici/pull/907 - if (resume) { - this[kResume] = null - resume() - } - } - _destroy (err, callback) { - this._read() - callback(err) - } -} +const assert = __nccwpck_require__(2613) +const { Readable } = __nccwpck_require__(2203) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440) -class PipelineResponse extends Readable { - constructor (resume) { - super({ autoDestroy: true }) - this[kResume] = resume - } +let Blob - _read () { - this[kResume]() +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') + +const noop = () => {} + +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false } - _destroy (err, callback) { + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } + if (!err && !this._readableState.endEmitted) { err = new RequestAbortedError() } - callback(err) + if (err) { + this[kAbort]() + } + + return super.destroy(err) } -} -class PipelineHandler extends AsyncResource { - constructor (opts, handler) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + 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) + } - if (typeof handler !== 'function') { - throw new InvalidArgumentError('invalid handler') + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true } + return super.on(ev, ...args) + } - const { signal, method, opaque, onInfo, responseHeaders } = opts + addListener (ev, ...args) { + return this.on(ev, ...args) + } - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + 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 + } - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } + removeListener (ev, ...args) { + return this.off(ev, ...args) + } - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') + 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) + } - 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) + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } - this.ret = new Duplex({ - readableObjectMode: opts.objectMode, - autoDestroy: true, - read: () => { - const { body } = this + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } - if (body && body.resume) { - body.resume() - } - }, - write: (chunk, encoding, callback) => { - const { req } = this + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } - if (req.push(chunk, encoding) || req._readableState.destroyed) { - callback() - } else { - req[kResume] = callback - } - }, - destroy: (err, callback) => { - const { body, req, res, ret, abort } = this + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } - if (!err && !ret._readableState.endEmitted) { - err = new RequestAbortedError() - } + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } - if (abort && err) { - abort() - } + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } - util.destroy(body, err) - util.destroy(req, err) - util.destroy(res, err) + // 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] + } - removeSignal(this) + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal - callback(err) + if (signal) { + try { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + } catch (err) { + return Promise.reject(err) } - }).on('prefinish', () => { - const { req } = this + } - // Node < 15 does not call _final in same tick. - req.push(null) - }) + if (this.closed) { + return Promise.resolve(null) + } - this.res = null + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop - addSignal(this, signal) + this + .on('close', function () { + signalListenerCleanup() + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() + }) } +} - onConnect (abort, context) { - const { ret, res } = this - - assert(!res, 'pipeline cannot be retried') +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} - if (ret.destroyed) { - throw new RequestAbortedError() - } +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} - this.abort = abort - this.context = context +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') } - onHeaders (statusCode, rawHeaders, resume) { - const { opaque, handler, context } = this + assert(!stream[kConsume]) - if (statusCode < 200) { - if (this.onInfo) { - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.onInfo({ statusCode, headers }) - } - return + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] } - 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 + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) }) - } 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('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) } }) - .on('error', (err) => { - const { ret } = this - util.destroy(ret, err) - }) - .on('end', () => { - const { ret } = this + process.nextTick(consumeStart, stream[kConsume]) + }) +} - ret.push(null) - }) - .on('close', () => { - const { ret } = this +function consumeStart (consume) { + if (consume.body === null) { + return + } - if (!ret._readableState.ended) { - util.destroy(ret, new RequestAbortedError()) - } - }) + const { _readableState: state } = consume.stream - this.body = body + for (const chunk of state.buffer) { + consumePush(consume, chunk) } - onData (chunk) { - const { res } = this - return res.push(chunk) + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) } - onComplete (trailers) { - const { res } = this - res.push(null) - } + consume.stream.resume() - onError (err) { - const { ret } = this - this.handler = null - util.destroy(ret, err) + while (consume.stream.read() != null) { + // Loop } } -function pipeline (opts, handler) { +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + try { - const pipelineHandler = new PipelineHandler(opts, handler) - this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) - return pipelineHandler.ret + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } + + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = (__nccwpck_require__(181).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) + } + + consumeFinish(consume) } catch (err) { - return new PassThrough().destroy(err) + stream.destroy(err) } } -module.exports = pipeline +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() + } -/***/ 4043: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} +/***/ }), -const Readable = __nccwpck_require__(9927) +/***/ 7655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(2613) const { - InvalidArgumentError, - RequestAbortedError + ResponseStatusCodeError } = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class RequestHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { - throw new InvalidArgumentError('invalid highWaterMark') - } - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } +const { toUSVString } = __nccwpck_require__(3440) - super('UNDICI_REQUEST') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) - 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 + let chunks = [] + let limit = 0 - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break } - - addSignal(this, signal) } - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return } - 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 }) - } + 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 } - 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 - }) - } + 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 } - onData (chunk) { - const { res } = this - return res.push(chunk) - } + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} - onComplete (trailers) { - const { res } = this +module.exports = { getResolveErrorBodyCallback } - removeSignal(this) - util.parseHeaders(trailers, this.trailers) +/***/ }), - res.push(null) - } +/***/ 1093: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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 }) - }) - } +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8707) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(8640) +const Pool = __nccwpck_require__(5076) +const { kUrl, kInterceptors } = __nccwpck_require__(6443) +const { parseOrigin } = __nccwpck_require__(3440) +const kFactory = Symbol('factory') - if (res) { - this.res = null - // Ensure all queued handlers are invoked before destroying res. - queueMicrotask(() => { - util.destroy(res, err) - }) - } +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') - if (body) { - this.body = null - util.destroy(body, err) - } - } +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) } -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 })) - } +function defaultFactory (origin, opts) { + return new Pool(origin, opts) } -module.exports = request -module.exports.RequestHandler = RequestHandler +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] + } -/***/ 3560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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() + } -const { finished, PassThrough } = __nccwpck_require__(2203) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin -class StreamHandler extends AsyncResource { - constructor (opts, factory, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + 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])) - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) - if (typeof factory !== 'function') { - throw new InvalidArgumentError('invalid factory') + 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() } + }) - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } + this._updateBalancedPoolStats() - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } + return this + } - super('UNDICI_STREAM') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } - 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 + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) } - addSignal(this, signal) + return this } - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() + 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() } - this.abort = abort - this.context = context - } + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { factory, opaque, context, callback, responseHeaders } = this + if (!dispatcher) { + return + } - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } + if (allClientsBusy) { return } - this.factory = null + let counter = 0 - let res + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - if (this.throwOnError && statusCode >= 400) { - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - res = new PassThrough() + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] - this.callback = null - this.runInAsyncScope(getResolveErrorBodyCallback, null, - { callback, body: res, contentType, statusCode, statusMessage, headers } - ) - } else { - if (factory === null) { - return + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] } - res = this.runInAsyncScope(factory, null, { - statusCode, - headers, - opaque, - context - }) + // 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 ( - !res || - typeof res.write !== 'function' || - typeof res.end !== 'function' || - typeof res.on !== 'function' - ) { - throw new InvalidReturnValueError('expected Writable') + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } - // 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[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} - this.callback = null - this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) +module.exports = BalancedPool - if (err) { - abort() - } - }) - } - res.on('drain', resume) +/***/ }), - this.res = res +/***/ 479: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - const needDrain = res.writableNeedDrain !== undefined - ? res.writableNeedDrain - : res._writableState && res._writableState.needDrain - return needDrain !== true - } - onData (chunk) { - const { res } = this +const { kConstruct } = __nccwpck_require__(296) +const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) +const { kHeadersList } = __nccwpck_require__(6443) +const { webidl } = __nccwpck_require__(4222) +const { Response, cloneResponse } = __nccwpck_require__(8676) +const { Request } = __nccwpck_require__(5194) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) +const { fetching } = __nccwpck_require__(2315) +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523) +const assert = __nccwpck_require__(2613) +const { getGlobalDispatcher } = __nccwpck_require__(2581) - return res ? res.write(chunk) : true - } +/** + * @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 + */ - onComplete (trailers) { - const { res } = this +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ - removeSignal(this) +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList - if (!res) { - return + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() } - this.trailers = util.parseHeaders(trailers) - - res.end() + this.#relevantRequestResponseList = arguments[1] } - onError (err) { - const { res, callback, opaque, body } = this - - removeSignal(this) + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) - this.factory = null + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - if (res) { - this.res = null - util.destroy(res, err) - } else if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } + const p = await this.matchAll(request, options) - if (body) { - this.body = null - util.destroy(body, err) + if (p.length === 0) { + return } - } -} - -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 })) + return p[0] } -} -module.exports = stream + 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 -/***/ 1882: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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 = [] -const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) -const { AsyncResource } = __nccwpck_require__(290) -const util = __nccwpck_require__(3440) -const { addSignal, removeSignal } = __nccwpck_require__(158) -const assert = __nccwpck_require__(2613) + // 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) -class UpgradeHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } } - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! - const { signal, opaque, responseHeaders } = opts + // 5.5.1 + const responseList = [] - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + // 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) } - super('UNDICI_UPGRADE') + // 6. + return Object.freeze(responseList) + } - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.abort = null - this.context = null + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) - addSignal(this, signal) - } + request = webidl.converters.RequestInfo(request) - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } + // 1. + const requests = [request] - this.abort = abort - this.context = null - } + // 2. + const responseArrayPromise = this.addAll(requests) - onHeaders () { - throw new SocketError('bad upgrade', null) + // 3. + return await responseArrayPromise } - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - assert.strictEqual(statusCode, 101) + requests = webidl.converters['sequence'](requests) - removeSignal(this) + // 1. + const responsePromises = [] - this.callback = null - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.runInAsyncScope(callback, null, null, { - headers, - socket, - opaque, - context - }) - } + // 2. + const requestList = [] - onError (err) { - const { callback, opaque } = this + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } - removeSignal(this) + // 3.1 + const r = request[kState] - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) + // 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.' + }) + } } - } -} -function upgrade (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - upgrade.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] - 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 })) - } -} + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] -module.exports = upgrade + // 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) -/***/ 6615: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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' + })) -module.exports.request = __nccwpck_require__(4043) -module.exports.stream = __nccwpck_require__(3560) -module.exports.pipeline = __nccwpck_require__(6862) -module.exports.upgrade = __nccwpck_require__(1882) -module.exports.connect = __nccwpck_require__(4660) + 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) + } + })) -/***/ 9927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 5.8 + responsePromises.push(responsePromise.promise) + } -// Ported from https://github.com/nodejs/undici/pull/907 + // 6. + const p = Promise.all(responsePromises) + // 7. + const responses = await p + // 7.1 + const operations = [] -const assert = __nccwpck_require__(2613) -const { Readable } = __nccwpck_require__(2203) -const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440) + // 7.2 + let index = 0 -let Blob + // 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 + } -const kConsume = Symbol('kConsume') -const kReading = Symbol('kReading') -const kBody = Symbol('kBody') -const kAbort = Symbol('abort') -const kContentType = Symbol('kContentType') + operations.push(operation) // 7.3.5 -const noop = () => {} + index++ // 7.3.6 + } -module.exports = class BodyReadable extends Readable { - constructor ({ - resume, - abort, - contentType = '', - highWaterMark = 64 * 1024 // Same as nodejs fs streams. - }) { - super({ - autoDestroy: true, - read: resume, - highWaterMark - }) + // 7.5 + const cacheJobPromise = createDeferredPromise() - this._readableState.dataEmitted = false + // 7.6.1 + let errorData = null - this[kAbort] = abort - this[kConsume] = null - this[kBody] = null - this[kContentType] = contentType + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } - // 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 + // 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 } - destroy (err) { - if (this.destroyed) { - // Node < 16 - return this + 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] } - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() + // 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' + }) } - if (err) { - this[kAbort]() + // 5. + const innerResponse = response[kState] + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) } - return super.destroy(err) - } + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) - emit (ev, ...args) { - if (ev === 'data') { - // Node < 16.7 - this._readableState.dataEmitted = true - } else if (ev === 'error') { - // Node < 16 - this._readableState.errorEmitted = true + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } } - return super.emit(ev, ...args) - } - on (ev, ...args) { - if (ev === 'data' || ev === 'readable') { - this[kReading] = true + // 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' + }) } - return super.on(ev, ...args) - } - addListener (ev, ...args) { - return this.on(ev, ...args) - } + // 9. + const clonedResponse = cloneResponse(innerResponse) - off (ev, ...args) { - const ret = super.off(ev, ...args) - if (ev === 'data' || ev === 'readable') { - this[kReading] = ( - this.listenerCount('data') > 0 || - this.listenerCount('readable') > 0 - ) + // 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) } - return ret - } - removeListener (ev, ...args) { - return this.off(ev, ...args) - } + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] - push (chunk) { - if (this[kConsume] && chunk !== null && this.readableLength === 0) { - consumePush(this[kConsume], chunk) - return this[kReading] ? super.push(chunk) : true + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. } - return super.push(chunk) - } - // https://fetch.spec.whatwg.org/#dom-body-text - async text () { - return consume(this, 'text') - } + // 17. + operations.push(operation) - // https://fetch.spec.whatwg.org/#dom-body-json - async json () { - return consume(this, 'json') - } + // 19. + const bytes = await bodyReadPromise.promise - // https://fetch.spec.whatwg.org/#dom-body-blob - async blob () { - return consume(this, 'blob') - } + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } - // https://fetch.spec.whatwg.org/#dom-body-arraybuffer - async arrayBuffer () { - return consume(this, 'arrayBuffer') - } + // 19.1 + const cacheJobPromise = createDeferredPromise() - // https://fetch.spec.whatwg.org/#dom-body-formdata - async formData () { - // TODO: Implement. - throw new NotSupportedError() - } + // 19.2.1 + let errorData = null - // https://fetch.spec.whatwg.org/#dom-body-bodyused - get bodyUsed () { - return util.isDisturbed(this) - } + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } - // 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) + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) } - } - return this[kBody] + }) + + return cacheJobPromise.promise } - dump (opts) { - let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 - const signal = opts && opts.signal + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - if (signal) { - try { - if (typeof signal !== 'object' || !('aborted' in signal)) { - throw new InvalidArgumentError('signal must be an AbortSignal') - } - util.throwIfAborted(signal) - } catch (err) { - return Promise.reject(err) + 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') - if (this.closed) { - return Promise.resolve(null) + r = new Request(request)[kState] } - return new Promise((resolve, reject) => { - const signalListenerCleanup = signal - ? util.addAbortListener(signal, () => { - this.destroy() - }) - : noop - - this - .on('close', function () { - signalListenerCleanup() - if (signal && signal.aborted) { - reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) - } else { - resolve(null) - } - }) - .on('error', noop) - .on('data', function (chunk) { - limit -= chunk.length - if (limit <= 0) { - this.destroy() - } - }) - .resume() - }) - } -} + /** @type {CacheBatchOperation[]} */ + const operations = [] -// https://streams.spec.whatwg.org/#readablestream-locked -function isLocked (self) { - // Consume is an implicit lock. - return (self[kBody] && self[kBody].locked === true) || self[kConsume] -} + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } -// https://fetch.spec.whatwg.org/#body-unusable -function isUnusable (self) { - return util.isDisturbed(self) || isLocked(self) -} + operations.push(operation) -async function consume (stream, type) { - if (isUnusable(stream)) { - throw new TypeError('unusable') - } + const cacheJobPromise = createDeferredPromise() - assert(!stream[kConsume]) + let errorData = null + let requestResponses - return new Promise((resolve, reject) => { - stream[kConsume] = { - type, - stream, - resolve, - reject, - length: 0, - body: [] + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e } - 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]) - }) -} + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) -function consumeStart (consume) { - if (consume.body === null) { - return + return cacheJobPromise.promise } - const { _readableState: state } = consume.stream + /** + * @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) - for (const chunk of state.buffer) { - consumePush(consume, chunk) - } + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) - if (state.endEmitted) { - consumeEnd(this[kConsume]) - } else { - consume.stream.on('end', function () { - consumeEnd(this[kConsume]) - }) - } + // 1. + let r = null - consume.stream.resume() + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] - while (consume.stream.read() != null) { - // Loop - } -} + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } -function consumeEnd (consume) { - const { type, body, resolve, stream, length } = consume + // 4. + const promise = createDeferredPromise() - 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) + // 5. + // 5.1 + const requests = [] - let pos = 0 - for (const buf of body) { - dst.set(buf, pos) - pos += buf.byteLength + // 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) - resolve(dst.buffer) - } else if (type === 'blob') { - if (!Blob) { - Blob = (__nccwpck_require__(181).Blob) + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) } - resolve(new Blob(body, { type: stream[kContentType] })) } - consumeFinish(consume) - } catch (err) { - stream.destroy(err) - } -} + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] -function consumePush (consume, chunk) { - consume.length += chunk.length - consume.body.push(chunk) -} + // 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 -function consumeFinish (consume, err) { - if (consume.body === null) { - return - } + // 5.4.2.1 + requestList.push(requestObject) + } - if (err) { - consume.reject(err) - } else { - consume.resolve() - } + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) - consume.type = null - consume.stream = null - consume.resolve = null - consume.reject = null - consume.length = 0 - consume.body = null -} + 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] -/***/ 7655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 3. + const addedItems = [] -const assert = __nccwpck_require__(2613) -const { - ResponseStatusCodeError -} = __nccwpck_require__(8707) -const { toUSVString } = __nccwpck_require__(3440) + // 4.1 + const resultList = [] -async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { - assert(body) + 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"' + }) + } - let chunks = [] - let limit = 0 + // 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' + }) + } - for await (const chunk of body) { - chunks.push(chunk) - limit += chunk.length - if (limit > 128 * 1024) { - chunks = null - break - } - } + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } - if (statusCode === 204 || !contentType || !chunks) { - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) - return - } + // 4.2.4 + let requestResponses - 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 - } + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) - 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 - } + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) -} + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) -module.exports = { getResolveErrorBodyCallback } + // 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' + }) + } -/***/ 1093: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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) -const { - BalancedPoolMissingUpstreamError, - InvalidArgumentError -} = __nccwpck_require__(8707) -const { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} = __nccwpck_require__(8640) -const Pool = __nccwpck_require__(5076) -const { kUrl, kInterceptors } = __nccwpck_require__(6443) -const { parseOrigin } = __nccwpck_require__(3440) -const kFactory = Symbol('factory') - -const kOptions = Symbol('options') -const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') -const kCurrentWeight = Symbol('kCurrentWeight') -const kIndex = Symbol('kIndex') -const kWeight = Symbol('kWeight') -const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') -const kErrorPenalty = Symbol('kErrorPenalty') - -function getGreatestCommonDivisor (a, b) { - if (b === 0) return a - return getGreatestCommonDivisor(b, a % b) -} - -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) -class BalancedPool extends PoolBase { - constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { - super() + // 4.2.6.7.1 + cache.splice(idx, 1) + } - this[kOptions] = opts - this[kIndex] = -1 - this[kCurrentWeight] = 0 + // 4.2.6.8 + cache.push([operation.request, operation.response]) - this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 - this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } - if (!Array.isArray(upstreams)) { - upstreams = [upstreams] - } + // 4.2.7 + resultList.push([operation.request, operation.response]) + } - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 - this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) - ? opts.interceptors.BalancedPool - : [] - this[kFactory] = factory + // 5.2 + this.#relevantRequestResponseList = backupCache - for (const upstream of upstreams) { - this.addUpstream(upstream) + // 5.3 + throw e } - 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]) - }) + /** + * @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 = [] - pool.on('connectionError', () => { - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - }) + const storage = targetStorage ?? this.#relevantRequestResponseList - 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 requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) } - }) - - 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) + return resultList } - removeUpstream (upstream) { - const upstreamOrigin = parseOrigin(upstream).origin - - const pool = this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - )) + /** + * @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 + // } - if (pool) { - this[kRemoveClient](pool) - } + const queryURL = new URL(requestQuery.url) - return this - } + const cachedURL = new URL(request.url) - get upstreams () { - return this[kClients] - .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) - .map((p) => p[kUrl].origin) - } + if (options?.ignoreSearch) { + cachedURL.search = '' - [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() + queryURL.search = '' } - const dispatcher = this[kClients].find(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - - if (!dispatcher) { - return + if (!urlEquals(queryURL, cachedURL, true)) { + return false } - const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - - if (allClientsBusy) { - return + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true } - 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]] + const fieldValues = getFieldValues(response.headersList.get('vary')) - // find pool index with the largest weight - if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { - maxWeightIndex = this[kIndex] + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false } - // 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] + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) - if (this[kCurrentWeight] <= 0) { - this[kCurrentWeight] = this[kMaxWeightPerServer] - } - } - if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { - return pool + // 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 } } - this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] - this[kIndex] = maxWeightIndex - return this[kClients][maxWeightIndex] + return true } } -module.exports = BalancedPool +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 +} /***/ }), -/***/ 479: +/***/ 4738: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { const { kConstruct } = __nccwpck_require__(296) -const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993) -const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) -const { kHeadersList } = __nccwpck_require__(6443) +const { Cache } = __nccwpck_require__(479) const { webidl } = __nccwpck_require__(4222) -const { Response, cloneResponse } = __nccwpck_require__(8676) -const { Request } = __nccwpck_require__(5194) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const { fetching } = __nccwpck_require__(2315) -const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523) -const assert = __nccwpck_require__(2613) -const { getGlobalDispatcher } = __nccwpck_require__(2581) - -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation - * @typedef {Object} CacheBatchOperation - * @property {'delete' | 'put'} type - * @property {any} request - * @property {any} response - * @property {import('../../types/cache').CacheQueryOptions} options - */ - -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list - * @typedef {[any, any][]} requestResponseList - */ +const { kEnumerableProperty } = __nccwpck_require__(3440) -class Cache { +class CacheStorage { /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list - * @type {requestResponseList} + * @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) } - async matchAll (request = undefined, options = {}) { - webidl.brandCheck(this, Cache) + /** + * @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' }) - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) + cacheName = webidl.converters.DOMString(cacheName) - // 1. - let r = null + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') - // 2. - if (request !== undefined) { - if (request instanceof Request) { - // 2.1.1 - r = request[kState] + // 2.1.1 + const cache = this.#caches.get(cacheName) - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { - // 2.2.1 - r = new Request(request)[kState] - } + // 2.1.1.1 + return new Cache(kConstruct, cache) } - // 5. - // 5.1 - const responses = [] + // 2.2 + const cache = [] - // 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) + // 2.3 + this.#caches.set(cacheName, cache) - // 5.3.2 - for (const requestResponse of requestResponses) { - responses.push(requestResponse[1]) - } - } + // 2.4 + return new Cache(kConstruct, cache) + } - // 5.4 - // We don't implement CORs so we don't need to loop over the responses, yay! + /** + * @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' }) - // 5.5.1 - const responseList = [] + cacheName = webidl.converters.DOMString(cacheName) - // 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' + return this.#caches.delete(cacheName) + } - responseList.push(responseObject) - } + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) - // 6. - return Object.freeze(responseList) + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] } +} - async add (request) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) - request = webidl.converters.RequestInfo(request) +module.exports = { + CacheStorage +} - // 1. - const requests = [request] - // 2. - const responseArrayPromise = this.addAll(requests) +/***/ }), - // 3. - return await responseArrayPromise - } +/***/ 296: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - async addAll (requests) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - requests = webidl.converters['sequence'](requests) - // 1. - const responsePromises = [] +module.exports = { + kConstruct: (__nccwpck_require__(6443).kConstruct) +} - // 2. - const requestList = [] - // 3. - for (const request of requests) { - if (typeof request === 'string') { - continue - } +/***/ }), - // 3.1 - const r = request[kState] +/***/ 3993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) +const assert = __nccwpck_require__(2613) +const { URLSerializer } = __nccwpck_require__(4322) +const { isValidHeaderName } = __nccwpck_require__(5523) - // 5.6 - const responsePromise = createDeferredPromise() +/** + * @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) - // 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')) + const serializedB = URLSerializer(B, excludeFragment) - // 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' - })) + return serializedA === serializedB +} - for (const controller of fetchControllers) { - controller.abort() - } +/** + * @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) - return - } - } - } - }, - processResponseEndOfBody (response) { - // 1. - if (response.aborted) { - responsePromise.reject(new DOMException('aborted', 'AbortError')) - return - } + const values = [] - // 2. - responsePromise.resolve(response) - } - })) + for (let value of header.split(',')) { + value = value.trim() - // 5.8 - responsePromises.push(responsePromise.promise) + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue } - // 6. - const p = Promise.all(responsePromises) + values.push(value) + } - // 7. - const responses = await p + return values +} - // 7.1 - const operations = [] +module.exports = { + urlEquals, + fieldValues +} - // 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 +/***/ 6197: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - index++ // 7.3.6 - } +// @ts-check - // 7.5 - const cacheJobPromise = createDeferredPromise() - // 7.6.1 - let errorData = null - // 7.6.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } +/* global WebAssembly */ - // 7.6.3 - queueMicrotask(() => { - // 7.6.3.1 - if (errorData === null) { - cacheJobPromise.resolve(undefined) - } else { - // 7.6.3.2 - cacheJobPromise.reject(errorData) - } - }) +const assert = __nccwpck_require__(2613) +const net = __nccwpck_require__(9278) +const http = __nccwpck_require__(8611) +const { pipeline } = __nccwpck_require__(2203) +const util = __nccwpck_require__(3440) +const timers = __nccwpck_require__(8804) +const Request = __nccwpck_require__(4655) +const DispatcherBase = __nccwpck_require__(1) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = __nccwpck_require__(8707) +const buildConnector = __nccwpck_require__(9136) +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest +} = __nccwpck_require__(6443) - // 7.7 - return cacheJobPromise.promise +/** @type {import('http2')} */ +let http2 +try { + http2 = __nccwpck_require__(5675) +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS } +} = http2 - async put (request, response) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) +// Experimental +let h2ExperimentalWarned = false - request = webidl.converters.RequestInfo(request) - response = webidl.converters.Response(response) +const FastBuffer = Buffer[Symbol.species] - // 1. - let innerRequest = null +const kClosedResolve = Symbol('kClosedResolve') - // 2. - if (request instanceof Request) { - innerRequest = request[kState] - } else { // 3. - innerRequest = new Request(request)[kState] - } +const channels = {} - // 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' - }) - } +try { + const diagnosticsChannel = __nccwpck_require__(1637) + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} - // 5. - const innerResponse = response[kState] +/** + * @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() - // 6. - if (innerResponse.status === 206) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got 206 status' - }) + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') } - // 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' - }) - } - } + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') } - // 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' - }) + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') } - // 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) + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') } - // 12. - /** @type {CacheBatchOperation[]} */ - const operations = [] - - // 13. - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 14. - request: innerRequest, // 15. - response: clonedResponse // 16. + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') } - // 17. - operations.push(operation) - - // 19. - const bytes = await bodyReadPromise.promise - - if (clonedResponse.body != null) { - clonedResponse.body.source = bytes + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') } - // 19.1 - const cacheJobPromise = createDeferredPromise() - - // 19.2.1 - let errorData = null + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } - // 19.2.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') } - // 19.2.3 - queueMicrotask(() => { - // 19.2.3.1 - if (errorData === null) { - cacheJobPromise.resolve() - } else { // 19.2.3.2 - cacheJobPromise.reject(errorData) - } - }) + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } - return cacheJobPromise.promise - } + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } - async delete (request, options = {}) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } - request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } - /** - * @type {Request} - */ - let r = null + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } - if (request instanceof Request) { - r = request[kState] + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } - if (r.method !== 'GET' && !options.ignoreMethod) { - return false - } - } else { - assert(typeof request === 'string') + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } - r = new Request(request)[kState] + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') } - /** @type {CacheBatchOperation[]} */ - const operations = [] + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } - /** @type {CacheBatchOperation} */ - const operation = { - type: 'delete', - request: r, - options + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') } - operations.push(operation) + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } - const cacheJobPromise = createDeferredPromise() + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } - let errorData = null - let requestResponses + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + } - try { - requestResponses = this.#batchCacheOperations(operations) - } catch (e) { - errorData = e + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) } - queueMicrotask(() => { - if (errorData === null) { - cacheJobPromise.resolve(!!requestResponses?.length) - } else { - cacheJobPromise.reject(errorData) - } - }) + 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' - return cacheJobPromise.promise + // 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 } - /** - * @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) + get pipelining () { + return this[kPipelining] + } - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } - // 1. - let r = null + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } - // 2. - if (request !== undefined) { - // 2.1 - if (request instanceof Request) { - // 2.1.1 - r = request[kState] + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { // 2.2 - r = new Request(request)[kState] - } + 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) } - // 4. - const promise = createDeferredPromise() + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } - // 5. - // 5.1 - const requests = [] + return this[kNeedDrain] < 2 + } - // 5.2 - if (request === undefined) { - // 5.2.1 - for (const requestResponse of this.#relevantRequestResponseList) { - // 5.2.1.1 - requests.push(requestResponse[0]) + 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 } - } 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]) + 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) } - } - // 5.4 - queueMicrotask(() => { - // 5.4.1 - const requestList = [] + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } - // 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 + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } - // 5.4.2.1 - requestList.push(requestObject) + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) } - // 5.4.3 - promise.resolve(Object.freeze(requestList)) + resume(this) }) - - 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 +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - // 2. - const backupCache = [...cache] + this[kSocket][kError] = err - // 3. - const addedItems = [] + onError(this[kClient], err) +} - // 4.1 - const resultList = [] +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - 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"' - }) - } + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) + } +} - // 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' - }) - } +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} - // 4.2.3 - if (this.#queryCache(operation.request, operation.options, addedItems).length) { - throw new DOMException('???', 'InvalidStateError') - } +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 - // 4.2.4 - let requestResponses + if (client.destroyed) { + assert(this[kPending] === 0) - // 4.2.5 - if (operation.type === 'delete') { - // 4.2.5.1 - requestResponses = this.#queryCache(operation.request, operation.options) + // 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 - // TODO: the spec is wrong, this is needed to pass WPTs - if (requestResponses.length === 0) { - return [] - } + errorRequest(client, request, err) + } - // 4.2.5.2 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) + client[kPendingIdx] = client[kRunningIdx] - // 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' - }) - } + assert(client[kRunning] === 0) - // 4.2.6.2 - const r = operation.request + client.emit('disconnect', + client[kUrl], + [client], + err + ) - // 4.2.6.3 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'expected http or https scheme' - }) - } + resume(client) +} - // 4.2.6.4 - if (r.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'not get method' - }) - } +const constants = __nccwpck_require__(2824) +const createRedirectInterceptor = __nccwpck_require__(4415) +const EMPTY_BUF = Buffer.alloc(0) - // 4.2.6.5 - if (operation.options != null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'options must not be defined' - }) - } +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined - // 4.2.6.6 - requestResponses = this.#queryCache(operation.request) + let mod + try { + mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64')) + } catch (e) { + /* istanbul ignore next */ - // 4.2.6.7 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64')) + } - // 4.2.6.7.1 - cache.splice(idx, 1) - } + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ - // 4.2.6.8 - cache.push([operation.request, operation.response]) + 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 + } - // 4.2.6.10 - addedItems.push([operation.request, operation.response]) - } + /* eslint-enable camelcase */ + } + }) +} - // 4.2.7 - resultList.push([operation.request, operation.response]) - } +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() - // 4.3 - return resultList - } catch (e) { // 5. - // 5.1 - this.#relevantRequestResponseList.length = 0 +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null - // 5.2 - this.#relevantRequestResponseList = backupCache +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 - // 5.3 - throw e +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() + } } } - /** - * @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 = [] + resume () { + if (this.socket.destroyed || !this.paused) { + return + } - const storage = targetStorage ?? this.#relevantRequestResponseList + assert(this.ptr != null) + assert(currentParser == null) - for (const requestResponse of storage) { - const [cachedRequest, cachedResponse] = requestResponse - if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { - resultList.push(requestResponse) + 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() } } - return resultList + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() } - /** - * @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) + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } - if (options?.ignoreSearch) { - cachedURL.search = '' + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) - queryURL.search = '' - } + const { socket, llhttp } = this - if (!urlEquals(queryURL, cachedURL, true)) { - return false + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) } - if ( - response == null || - options?.ignoreVary || - !response.headersList.contains('vary') - ) { - return true - } + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - const fieldValues = getFieldValues(response.headersList.get('vary')) + // 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 - for (const fieldValue of fieldValues) { - if (fieldValue === '*') { - return false + 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 requestValue = request.headersList.get(fieldValue) - const queryValue = requestQuery.headersList.get(fieldValue) + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr - // 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 + 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) } - - 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 -}) + destroy () { + assert(this.ptr != null) + assert(currentParser == null) -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 - } -] + this.llhttp.llhttp_free(this.ptr) + this.ptr = null -webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null -webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ - ...cacheQueryOptionConverters, - { - key: 'cacheName', - converter: webidl.converters.DOMString + this.paused = false } -]) -webidl.converters.Response = webidl.interfaceConverter(Response) + onStatus (buf) { + this.statusText = buf.toString() + } -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.RequestInfo -) + onMessageBegin () { + const { socket, client } = this -module.exports = { - Cache -} + /* 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 -/***/ 4738: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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 -const { kConstruct } = __nccwpck_require__(296) -const { Cache } = __nccwpck_require__(479) -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } -class CacheStorage { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map - * @type {Map= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) } } - async match (request, options = {}) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' }) + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this - request = webidl.converters.RequestInfo(request) - options = webidl.converters.MultiCacheQueryOptions(options) + assert(upgrade) - // 1. - if (options.cacheName != null) { - // 1.1.1.1 - if (this.#caches.has(options.cacheName)) { - // 1.1.1.1.1 - const cacheList = this.#caches.get(options.cacheName) - const cache = new Cache(kConstruct, cacheList) + const request = client[kQueue][client[kRunningIdx]] + assert(request) - return await cache.match(request, options) - } - } else { // 2. - // 2.2 - for (const cacheList of this.#caches.values()) { - const cache = new Cache(kConstruct, cacheList) + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') - // 2.2.1.2 - const response = await cache.match(request, options) + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null - if (response !== undefined) { - return response - } - } - } - } + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-has - * @param {string} cacheName - * @returns {Promise} - */ - async has (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) + socket.unshift(head) - cacheName = webidl.converters.DOMString(cacheName) + socket[kParser].destroy() + socket[kParser] = null - // 2.1.1 - // 2.2 - return this.#caches.has(cacheName) - } + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) - /** - * @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' }) + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) - cacheName = webidl.converters.DOMString(cacheName) + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } - // 2.1 - if (this.#caches.has(cacheName)) { - // await caches.open('v1') !== await caches.open('v1') + resume(client) + } - // 2.1.1 - const cache = this.#caches.get(cacheName) + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this - // 2.1.1.1 - return new Cache(kConstruct, cache) + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 } - // 2.2 - const cache = [] + const request = client[kQueue][client[kRunningIdx]] - // 2.3 - this.#caches.set(cacheName, cache) + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } - // 2.4 - return new Cache(kConstruct, cache) - } + assert(!this.upgrade) + assert(this.statusCode < 200) - /** - * @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' }) + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } - cacheName = webidl.converters.DOMString(cacheName) + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } - return this.#caches.delete(cacheName) - } + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys - * @returns {string[]} - */ - async keys () { - webidl.brandCheck(this, CacheStorage) + 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') + ) - // 2.1 - const keys = this.#caches.keys() + 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() + } + } - // 2.2 - return [...keys] - } -} + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } -Object.defineProperties(CacheStorage.prototype, { - [Symbol.toStringTag]: { - value: 'CacheStorage', - configurable: true - }, - match: kEnumerableProperty, - has: kEnumerableProperty, - open: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty -}) + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } -module.exports = { - CacheStorage -} + 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 + } -/***/ 296: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + if (request.aborted) { + return -1 + } + if (request.method === 'HEAD') { + return 1 + } -module.exports = { - kConstruct: (__nccwpck_require__(6443).kConstruct) -} + if (statusCode < 200) { + return 1 + } + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } -/***/ }), + return pause ? constants.ERROR.PAUSED : 0 + } -/***/ 3993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + if (socket.destroyed) { + return -1 + } + const request = client[kQueue][client[kRunningIdx]] + assert(request) -const assert = __nccwpck_require__(2613) -const { URLSerializer } = __nccwpck_require__(4322) -const { isValidHeaderName } = __nccwpck_require__(5523) + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } -/** - * @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) + assert(statusCode >= 200) - const serializedB = URLSerializer(B, excludeFragment) + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } - return serializedA === serializedB -} + this.bytesRead += buf.length -/** - * @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) + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } - const values = [] + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this - for (let value of header.split(',')) { - value = value.trim() + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } - if (!value.length) { - continue - } else if (!isValidHeaderName(value)) { - continue + if (upgrade) { + return } - values.push(value) - } + const request = client[kQueue][client[kRunningIdx]] + assert(request) - return values -} - -module.exports = { - urlEquals, - fieldValues -} + 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 -/***/ 6197: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (statusCode < 200) { + return + } -// @ts-check + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + request.onComplete(headers) + client[kQueue][client[kRunningIdx]++] = null -/* global WebAssembly */ + 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) + } + } +} -const assert = __nccwpck_require__(2613) -const net = __nccwpck_require__(9278) -const http = __nccwpck_require__(8611) -const { pipeline } = __nccwpck_require__(2203) -const util = __nccwpck_require__(3440) -const timers = __nccwpck_require__(8804) -const Request = __nccwpck_require__(4655) -const DispatcherBase = __nccwpck_require__(1) -const { - RequestContentLengthMismatchError, - ResponseContentLengthMismatchError, - InvalidArgumentError, - RequestAbortedError, - HeadersTimeoutError, - HeadersOverflowError, - SocketError, - InformationalError, - BodyTimeoutError, - HTTPParserError, - ResponseExceededMaxSizeError, - ClientDestroyedError -} = __nccwpck_require__(8707) -const buildConnector = __nccwpck_require__(9136) -const { - kUrl, - kReset, - kServerName, - kClient, - kBusy, - kParser, - kConnect, - kBlocking, - kResuming, - kRunning, - kPending, - kSize, - kWriting, - kQueue, - kConnected, - kConnecting, - kNeedDrain, - kNoRef, - kKeepAliveDefaultTimeout, - kHostHeader, - kPendingIdx, - kRunningIdx, - kError, - kPipelining, - kSocket, - kKeepAliveTimeoutValue, - kMaxHeadersSize, - kKeepAliveMaxTimeout, - kKeepAliveTimeoutThreshold, - kHeadersTimeout, - kBodyTimeout, - kStrictContentLength, - kConnector, - kMaxRedirections, - kMaxRequests, - kCounter, - kClose, - kDestroy, - kDispatch, - kInterceptors, - kLocalAddress, - kMaxResponseSize, - kHTTPConnVersion, - // HTTP2 - kHost, - kHTTP2Session, - kHTTP2SessionState, - kHTTP2BuildRequest, - kHTTP2CopyHeaders, - kHTTP1BuildRequest -} = __nccwpck_require__(6443) +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser -/** @type {import('http2')} */ -let http2 -try { - http2 = __nccwpck_require__(5675) -} catch { - // @ts-ignore - http2 = { constants: {} } + /* 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')) + } } -const { - constants: { - HTTP2_HEADER_AUTHORITY, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_SCHEME, - HTTP2_HEADER_CONTENT_LENGTH, - HTTP2_HEADER_EXPECT, - HTTP2_HEADER_STATUS +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() } -} = http2 - -// Experimental -let h2ExperimentalWarned = false - -const FastBuffer = Buffer[Symbol.species] - -const kClosedResolve = Symbol('kClosedResolve') - -const channels = {} - -try { - const diagnosticsChannel = __nccwpck_require__(1637) - channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') - channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') - channels.connectError = diagnosticsChannel.channel('undici:client:connectError') - channels.connected = diagnosticsChannel.channel('undici:client:connected') -} catch { - channels.sendHeaders = { hasSubscribers: false } - channels.beforeConnect = { hasSubscribers: false } - channels.connectError = { hasSubscribers: false } - channels.connected = { hasSubscribers: false } } -/** - * @type {import('../types/client').default} - */ -class Client extends DispatcherBase { - /** - * - * @param {string|URL} url - * @param {import('../types/client').Client.Options} options - */ - constructor (url, { - interceptors, - maxHeaderSize, - headersTimeout, - socketTimeout, - requestTimeout, - connectTimeout, - bodyTimeout, - idleTimeout, - keepAlive, - keepAliveTimeout, - maxKeepAliveTimeout, - keepAliveMaxTimeout, - keepAliveTimeoutThreshold, - socketPath, - pipelining, - tls, - strictContentLength, - maxCachedSessions, - maxRedirections, - connect, - maxRequestsPerClient, - localAddress, - maxResponseSize, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - // h2 - allowH2, - maxConcurrentStreams - } = {}) { - super() - - if (keepAlive !== undefined) { - throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') - } +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this - if (socketTimeout !== undefined) { - throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') - } + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - if (requestTimeout !== undefined) { - throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + 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 } + } - if (idleTimeout !== undefined) { - throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') - } + this[kError] = err - if (maxKeepAliveTimeout !== undefined) { - throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') - } + onError(this[kClient], err) +} - if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { - throw new InvalidArgumentError('invalid maxHeaderSize') - } +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. - if (socketPath != null && typeof socketPath !== 'string') { - throw new InvalidArgumentError('invalid socketPath') - } + assert(client[kPendingIdx] === client[kRunningIdx]) - if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { - throw new InvalidArgumentError('invalid connectTimeout') + 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) + } +} - if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveTimeout') - } +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this - if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return } + } - if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { - throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') - } + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} - if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') - } +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this - if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + 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() } - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } + this[kParser].destroy() + this[kParser] = null + } - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { - throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') - } + client[kSocket] = null - if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { - throw new InvalidArgumentError('localAddress must be valid string IP address') - } + if (client.destroyed) { + assert(client[kPending] === 0) - if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { - throw new InvalidArgumentError('maxResponseSize must be a positive number') + // 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 - if ( - autoSelectFamilyAttemptTimeout != null && - (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) - ) { - throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') - } + errorRequest(client, request, err) + } - // h2 - if (allowH2 != null && typeof allowH2 !== 'boolean') { - throw new InvalidArgumentError('allowH2 must be a valid boolean value') - } + client[kPendingIdx] = client[kRunningIdx] - if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { - throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') - } + assert(client[kRunning] === 0) - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } + client.emit('disconnect', client[kUrl], [client], err) - 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' + resume(client) +} - // 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}` : ''}` +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) - // 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). + let { host, hostname, protocol, port } = client[kUrl] - this[kQueue] = [] - this[kRunningIdx] = 0 - this[kPendingIdx] = 0 - } + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') - get pipelining () { - return this[kPipelining] - } + assert(idx !== -1) + const ip = hostname.substring(1, idx) - set pipelining (value) { - this[kPipelining] = value - resume(this, true) + assert(net.isIP(ip)) + hostname = ip } - get [kPending] () { - return this[kQueue].length - this[kPendingIdx] - } + client[kConnecting] = true - get [kRunning] () { - return this[kPendingIdx] - this[kRunningIdx] + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) } - get [kSize] () { - return this[kQueue].length - this[kRunningIdx] - } + 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) + } + }) + }) - get [kConnected] () { - return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed - } + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return + } - get [kBusy] () { - const socket = this[kSocket] - return ( - (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || - (this[kSize] >= (this[kPipelining] || 1)) || - this[kPending] > 0 - ) - } + client[kConnecting] = false - /* istanbul ignore: only used for test */ - [kConnect] (cb) { - connect(this) - this.once('connect', cb) - } + assert(socket) - [kDispatch] (opts, handler) { - const origin = opts.origin || this[kUrl].origin + 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 request = this[kHTTPConnVersion] === 'h2' - ? Request[kHTTP2BuildRequest](origin, opts, handler) - : Request[kHTTP1BuildRequest](origin, opts, handler) + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) - 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) + 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 { - resume(this, true) - } + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } - if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { - this[kNeedDrain] = 2 + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) } - return this[kNeedDrain] < 2 - } + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null - 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 - } - }) - } + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) - 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) - } + client[kSocket] = socket - const callback = () => { - if (this[kClosedResolve]) { - // TODO (fix): Should we error here with ClientDestroyedError? - this[kClosedResolve]() - this[kClosedResolve] = null - } - resolve() - } + 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 + } - if (this[kHTTP2Session] != null) { - util.destroy(this[kHTTP2Session], err) - this[kHTTP2Session] = null - this[kHTTP2SessionState] = null - } + client[kConnecting] = false - if (!this[kSocket]) { - queueMicrotask(callback) - } else { - util.destroy(this[kSocket].on('close', callback), err) + 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) + } - resume(this) - }) + client.emit('connectionError', client[kUrl], [client], err) } -} - -function onHttp2SessionError (err) { - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - - this[kSocket][kError] = err - onError(this[kClient], err) + resume(client) } -function onHttp2FrameError (type, code, id) { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} - if (id === 0) { - this[kSocket][kError] = err - onError(this[kClient], err) +function resume (client, sync) { + if (client[kResuming] === 2) { + return } -} -function onHttp2SessionEnd () { - util.destroy(this, new SocketError('other side closed')) - util.destroy(this[kSocket], new SocketError('other side closed')) -} + client[kResuming] = 2 -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 + _resume(client, sync) + client[kResuming] = 0 - if (client.destroyed) { - assert(this[kPending] === 0) + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 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) +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return } - } else if (client[kRunning] > 0) { - // Fail head of pipeline. - const request = client[kQueue][client[kRunningIdx]] - client[kQueue][client[kRunningIdx]++] = null - errorRequest(client, request, err) - } + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } - client[kPendingIdx] = client[kRunningIdx] + const socket = client[kSocket] - assert(client[kRunning] === 0) + 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 + } - client.emit('disconnect', - client[kUrl], - [client], - err - ) + 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) + } + } + } - resume(client) -} + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } -const constants = __nccwpck_require__(2824) -const createRedirectInterceptor = __nccwpck_require__(4415) -const EMPTY_BUF = Buffer.alloc(0) + if (client[kPending] === 0) { + return + } -async function lazyllhttp () { - const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } - let mod - try { - mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64')) - } catch (e) { - /* istanbul ignore next */ + const request = client[kQueue][client[kPendingIdx]] - // We could check if the error was caused by the simd option not - // being enabled, but the occurring of this other error - // * https://github.com/emscripten-core/emscripten/issues/11495 - // got me to remove that check to avoid breaking Node 12. - mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64')) - } + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } - return await WebAssembly.instantiate(mod, { - env: { - /* eslint-disable camelcase */ + client[kServerName] = request.servername - 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 + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return } + } - /* eslint-enable camelcase */ + if (client[kConnecting]) { + return } - }) -} -let llhttpInstance = null -let llhttpPromise = lazyllhttp() -llhttpPromise.catch() + if (!socket && !client[kHTTP2Session]) { + connect(client) + return + } -let currentParser = null -let currentBufferRef = null -let currentBufferSize = 0 -let currentBufferPtr = null + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } -const TIMEOUT_HEADERS = 1 -const TIMEOUT_BODY = 2 -const TIMEOUT_IDLE = 3 + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } -class Parser { - constructor (client, socket, { exports }) { - assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + 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 + } - 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) + 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. - this.bytesRead = 0 + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } - this.keepAlive = '' - this.contentLength = '' - this.connection = '' - this.maxResponseSize = client[kMaxResponseSize] + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } } +} - 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() - } - } +// 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 } - resume () { - if (this.socket.destroyed || !this.paused) { - return - } + const { body, method, path, host, upgrade, headers, blocking, reset } = request - assert(this.ptr != null) - assert(currentParser == null) + // 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 - this.llhttp.llhttp_resume(this.ptr) + // 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. - assert(this.timeoutType === TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - this.paused = false - this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. - this.readMore() + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) } - readMore () { - while (!this.paused && this.ptr) { - const chunk = this.socket.read() - if (chunk === null) { - break - } - this.execute(chunk) - } + const bodyLength = util.bodyLength(body) + + let contentLength = bodyLength + + if (contentLength === null) { + contentLength = request.contentLength } - execute (data) { - assert(this.ptr != null) - assert(currentParser == null) - assert(!this.paused) + 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. - const { socket, llhttp } = this + contentLength = null + } - if (data.length > currentBufferSize) { - if (currentBufferPtr) { - llhttp.free(currentBufferPtr) - } - currentBufferSize = Math.ceil(data.length / 4096) * 4096 - currentBufferPtr = llhttp.malloc(currentBufferSize) + // 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 } - new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + process.emitWarning(new RequestContentLengthMismatchError()) + } - // 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 + const socket = client[kSocket] - 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 + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return } - const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + errorRequest(client, request, err || new RequestAbortedError()) - 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) - } + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) } - destroy () { - assert(this.ptr != null) - assert(currentParser == null) - - this.llhttp.llhttp_free(this.ptr) - this.ptr = null + if (request.aborted) { + return false + } - timers.clearTimeout(this.timeout) - this.timeout = null - this.timeoutValue = null - this.timeoutType = null + 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. - this.paused = false + socket[kReset] = true } - onStatus (buf) { - this.statusText = buf.toString() + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true } - onMessageBegin () { - const { socket, client } = this + if (reset != null) { + socket[kReset] = reset + } - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } - const request = client[kQueue][client[kRunningIdx]] - if (!request) { - return -1 - } + if (blocking) { + socket[kBlocking] = true } - onHeaderField (buf) { - const len = this.headers.length + let header = `${method} ${path} HTTP/1.1\r\n` - if ((len & 1) === 0) { - this.headers.push(buf) - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } - this.trackHeader(buf.length) + 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' } - onHeaderValue (buf) { - let len = this.headers.length + if (headers) { + header += headers + } - if ((len & 1) === 1) { - this.headers.push(buf) - len += 1 + 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 { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + 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') - 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() + 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 } - - this.trackHeader(buf.length) - } - - trackHeader (len) { - this.headersSize += len - if (this.headersSize >= this.headersMaxSize) { - util.destroy(this.socket, new HeadersOverflowError()) + } 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) } - 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) + return true +} - socket[kParser].destroy() - socket[kParser] = null +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - socket[kClient] = null - socket[kError] = null - socket - .removeListener('error', onSocketError) - .removeListener('readable', onSocketReadable) - .removeListener('end', onSocketEnd) - .removeListener('close', onSocketClose) + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders - client[kSocket] = null - client[kQueue][client[kRunningIdx]++] = null - client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } - try { - request.onUpgrade(statusCode, headers, socket) - } catch (err) { - util.destroy(socket, err) - } + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } - resume(client) + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) } - 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 - } + if (request.aborted) { + return false + } - const request = client[kQueue][client[kRunningIdx]] + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] - /* istanbul ignore next: difficult to make a test case for */ - if (!request) { - return -1 - } + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method - assert(!this.upgrade) - assert(this.statusCode < 200) + 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 (statusCode === 100) { - util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) - return -1 + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) } - /* this can only happen if server is misbehaving */ - if (upgrade && !request.upgrade) { - util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) - return -1 - } + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) - assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + return true + } - 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') - ) + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT - 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() - } - } + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' - if (request.method === 'CONNECT') { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } + // 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 - if (upgrade) { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } + // 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. - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) - if (this.shouldKeepAlive && client[kPipelining]) { - const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } - 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 contentLength = util.bodyLength(body) - const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + if (contentLength == null) { + contentLength = request.contentLength + } - if (request.aborted) { - return -1 - } + 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. - if (request.method === 'HEAD') { - return 1 - } + contentLength = null + } - if (statusCode < 200) { - return 1 + // 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 } - if (socket[kBlocking]) { - socket[kBlocking] = false - resume(client) - } + process.emitWarning(new RequestContentLengthMismatchError()) + } - return pause ? constants.ERROR.PAUSED : 0 + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` } - onBody (buf) { - const { client, socket, statusCode, maxResponseSize } = this + session.ref() - if (socket.destroyed) { - return -1 - } + const shouldEndStream = method === 'GET' || method === 'HEAD' + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) - const request = client[kQueue][client[kRunningIdx]] - assert(request) + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } - assert.strictEqual(this.timeoutType, TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } + // Increment counter as we have new several streams open + ++h2State.openStreams - assert(statusCode >= 200) + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers - if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { - util.destroy(socket, new ResponseExceededMaxSizeError()) - return -1 + if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { + stream.pause() } + }) - this.bytesRead += buf.length + stream.once('end', () => { + request.onComplete([]) + }) - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() } - } - - onMessageComplete () { - const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + }) - if (socket.destroyed && (!statusCode || shouldKeepAlive)) { - return -1 + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) { + session.unref() } + }) - if (upgrade) { - return + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) } + }) - 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 - } + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) - /* istanbul ignore next: should be handled by llhttp? */ - if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { - util.destroy(socket, new ResponseContentLengthMismatchError()) - return -1 + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) } + }) - request.onComplete(headers) + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) - client[kQueue][client[kRunningIdx]++] = null + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) - 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) - } - } -} + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) -function onParserTimeout (parser) { - const { socket, timeoutType, client } = parser + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) - /* 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')) - } -} + return true -function onSocketReadable () { - const { [kParser]: parser } = this - if (parser) { - parser.readMore() + 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 onSocketError (err) { - const { [kClient]: client, [kParser]: parser } = this +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + 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() + } + } + ) - 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 + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) + + function onPipeData (chunk) { + request.onBodySent(chunk) } - } - this[kError] = err + return + } - onError(this[kClient], err) -} + let finished = false -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. + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - assert(client[kPendingIdx] === client[kRunningIdx]) + const onData = function (chunk) { + if (finished) { + return + } - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(client, request, err) + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) } - assert(client[kSize] === 0) } -} - -function onSocketEnd () { - const { [kParser]: parser, [kClient]: client } = this + const onDrain = function () { + if (finished) { + return + } - if (client[kHTTPConnVersion] !== 'h2') { - if (parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() + if (body.resume) { + body.resume() + } + } + const onAbort = function () { + if (finished) { return } + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) } - - 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() + const onFinished = function (err) { + if (finished) { + return } - this[kParser].destroy() - this[kParser] = null - } + finished = true - const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) - client[kSocket] = null + socket + .off('drain', onDrain) + .off('error', onFinished) - if (client.destroyed) { - assert(client[kPending] === 0) + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) - // 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) + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } } - } 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) - } + writer.destroy(err) - client[kPendingIdx] = client[kRunningIdx] + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } - assert(client[kRunning] === 0) + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) - client.emit('disconnect', client[kUrl], [client], err) + if (body.resume) { + body.resume() + } - resume(client) + socket + .on('drain', onDrain) + .on('error', onFinished) } -async function connect (client) { - assert(!client[kConnecting]) - assert(!client[kSocket]) +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') - let { host, hostname, protocol, port } = client[kUrl] + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } - // Resolve ipv6 - if (hostname[0] === '[') { - const idx = hostname.indexOf(']') + const buffer = Buffer.from(await body.arrayBuffer()) - assert(idx !== -1) - const ip = hostname.substring(1, idx) + 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() + } - assert(net.isIP(ip)) - hostname = ip + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) } +} - client[kConnecting] = true +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - if (channels.beforeConnect.hasSubscribers) { - channels.beforeConnect.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector] - }) + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } } - 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) - } - }) - }) + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) - if (client.destroyed) { - util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) - return + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve } + }) - client[kConnecting] = false + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) - assert(socket) + 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 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 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) + } - const session = http2.connect(client[kUrl], { - createConnection: () => socket, - peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams - }) + return + } - 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() + socket + .on('close', onDrain) + .on('drain', onDrain) - client[kHTTP2Session] = session - socket[kHTTP2Session] = session - } else { - if (!llhttpInstance) { - llhttpInstance = await llhttpPromise - llhttpPromise = null + 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] } - socket[kNoRef] = false - socket[kWriting] = false - socket[kReset] = false - socket[kBlocking] = false - socket[kParser] = new Parser(client, socket, llhttpInstance) + if (!writer.write(chunk)) { + await waitForDrain() + } } - socket[kCounter] = 0 - socket[kMaxRequests] = client[kMaxRequests] - socket[kClient] = client - socket[kError] = null - + writer.end() + } catch (err) { + writer.destroy(err) + } finally { socket - .on('error', onSocketError) - .on('readable', onSocketReadable) - .on('end', onSocketEnd) - .on('close', onSocketClose) + .off('close', onDrain) + .off('drain', onDrain) + } +} - client[kSocket] = socket +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 - if (channels.connected.hasSubscribers) { - channels.connected.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - socket - }) + socket[kWriting] = true + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] } - client.emit('connect', client[kUrl], [client]) - } catch (err) { - if (client.destroyed) { - return + + if (socket.destroyed) { + return false } - client[kConnecting] = false + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } - if (channels.connectError.hasSubscribers) { - channels.connectError.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - error: err - }) + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) } - 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) + 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') } - } else { - onError(client, err) } - client.emit('connectionError', client[kUrl], [client], err) - } + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } - resume(client) -} + this.bytesWritten += len -function emitDrain (client) { - client[kNeedDrain] = 0 - client.emit('drain', client[kUrl], [client]) -} + const ret = socket.write(chunk) -function resume (client, sync) { - if (client[kResuming] === 2) { - return - } + socket.uncork() - client[kResuming] = 2 + request.onBodySent(chunk) - _resume(client, sync) - client[kResuming] = 0 + 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() + } + } + } - if (client[kRunningIdx] > 256) { - client[kQueue].splice(0, client[kRunningIdx]) - client[kPendingIdx] -= client[kRunningIdx] - client[kRunningIdx] = 0 + return ret } -} -function _resume (client, sync) { - while (true) { - if (client.destroyed) { - assert(client[kPending] === 0) - return + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] } - if (client[kClosedResolve] && !client[kSize]) { - client[kClosedResolve]() - client[kClosedResolve] = null + if (socket.destroyed) { 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 (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. - 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) - } + 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 (client[kBusy]) { - client[kNeedDrain] = 2 - } else if (client[kNeedDrain] === 2) { - if (sync) { - client[kNeedDrain] = 1 - process.nextTick(emitDrain, client) + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() } else { - emitDrain(client) + process.emitWarning(new RequestContentLengthMismatchError()) } - 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 (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() } } - 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 - } + resume(client) + } - 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. + destroy (err) { + const { socket, client } = this - // Request with stream or iterator body cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } + socket[kWriting] = false - if (!request.aborted && write(client, request)) { - client[kPendingIdx]++ - } else { - client[kQueue].splice(client[kPendingIdx], 1) + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) } } } -// 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 errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } } -function write (client, request) { - if (client[kHTTPConnVersion] === 'h2') { - writeH2(client, client[kHTTP2Session], request) - return - } +module.exports = Client - 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. +/***/ 3194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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) +/* istanbul ignore file: only for Node 12 */ - let contentLength = bodyLength +const { kConnected, kSize } = __nccwpck_require__(6443) - if (contentLength === null) { - contentLength = request.contentLength +class CompatWeakRef { + constructor (value) { + this.value = value } - 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. + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} - contentLength = null +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer } - // 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 + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) } + } +} - process.emitWarning(new RequestContentLengthMismatchError()) +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 } +} - const socket = client[kSocket] - try { - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } +/***/ }), - errorRequest(client, request, err || new RequestAbortedError()) +/***/ 9237: +/***/ ((module) => { - 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. +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 - socket[kReset] = true - } +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 - if (upgrade || method === 'CONNECT') { - // On CONNECT or upgrade, block pipeline from dispatching further - // requests on this connection. +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} - socket[kReset] = true - } - if (reset != null) { - socket[kReset] = reset - } +/***/ }), - if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { - socket[kReset] = true - } +/***/ 3168: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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] - } +const { parseSetCookie } = __nccwpck_require__(8915) +const { stringify } = __nccwpck_require__(3834) +const { webidl } = __nccwpck_require__(4222) +const { Headers } = __nccwpck_require__(6349) - 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' - } +/** + * @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 + */ - if (headers) { - header += headers - } +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) - if (channels.sendHeaders.hasSubscribers) { - channels.sendHeaders.publish({ request, headers: header, socket }) - } + webidl.brandCheck(headers, Headers, { strict: false }) - /* 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') + const cookie = headers.get('cookie') + const out = {} - 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) + if (!cookie) { + return out } - 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 + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') - if (upgrade) { - errorRequest(client, request, new Error('Upgrade not supported for H2')) - return false + out[name.trim()] = value.join('=') } - try { - // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } + return out +} - errorRequest(client, request, err || new RequestAbortedError()) - }) - } catch (err) { - errorRequest(client, request, err) - } +/** + * @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' }) - if (request.aborted) { - return false - } + webidl.brandCheck(headers, Headers, { strict: false }) - /** @type {import('node:http2').ClientHttp2Stream} */ - let stream - const h2State = client[kHTTP2SessionState] + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) - headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] - headers[HTTP2_HEADER_METHOD] = method + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} - 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 }) +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) - if (stream.id && !stream.pending) { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - } else { - stream.once('ready', () => { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - }) - } + webidl.brandCheck(headers, Headers, { strict: false }) - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) session.unref() - }) + const cookies = headers.getSetCookie() - return true + if (!cookies) { + return [] } - // https://tools.ietf.org/html/rfc7540#section-8.3 - // :path and :scheme headers must be omited when sending CONNECT + return cookies.map((pair) => parseSetCookie(pair)) +} - headers[HTTP2_HEADER_PATH] = path - headers[HTTP2_HEADER_SCHEME] = 'https' +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - // 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 + webidl.brandCheck(headers, Headers, { strict: false }) - // 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. + cookie = webidl.converters.Cookie(cookie) - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) + const str = stringify(cookie) - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) + if (str) { + headers.append('Set-Cookie', stringify(cookie)) } +} - let contentLength = util.bodyLength(body) - - if (contentLength == null) { - contentLength = request.contentLength +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 } +]) - 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 - } +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) + } - // 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}` + 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: [] } +]) - session.ref() - - const shouldEndStream = method === 'GET' || method === 'HEAD' - if (expectContinue) { - headers[HTTP2_HEADER_EXPECT] = '100-continue' - stream = session.request(headers, { endStream: shouldEndStream, signal }) - - stream.once('continue', writeBodyH2) - } else { - stream = session.request(headers, { - endStream: shouldEndStream, - signal - }) - writeBodyH2() - } +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} - // Increment counter as we have new several streams open - ++h2State.openStreams - stream.once('response', headers => { - const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers +/***/ }), - if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { - stream.pause() - } - }) +/***/ 8915: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - 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() - } - }) +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237) +const { isCTLExcludingHtab } = __nccwpck_require__(3834) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322) +const assert = __nccwpck_require__(2613) - stream.once('error', function (err) { - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) +/** + * @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 + } - stream.once('frameError', (type, code) => { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - errorRequest(client, request, err) + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) + // 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 } - // stream.on('aborted', () => { - // // TODO(HTTP/2): Support aborted - // }) + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: - // stream.on('timeout', () => { - // // TODO(HTTP/2): Support timeout - // }) + // 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 + } - // stream.on('push', headers => { - // // TODO(HTTP/2): Suppor push - // }) + // 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) + } - // stream.on('trailers', headers => { - // // TODO(HTTP/2): Support trailers - // }) + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() - return true + // 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 + } - 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) - } + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) } } -function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') +/** + * 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 + } - 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() - } - } - ) + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) - pipe.on('data', onPipeData) - pipe.once('end', () => { - pipe.removeListener('data', onPipeData) - util.destroy(pipe) - }) + let cookieAv = '' - function onPipeData (chunk) { - request.onBodySent(chunk) - } + // 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: - return + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' } - let finished = false + // Let the cookie-av string be the characters consumed in this step. - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + let attributeName = '' + let attributeValue = '' - const onData = function (chunk) { - if (finished) { - return - } + // 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 } - try { - if (!writer.write(chunk) && this.pause) { - this.pause() - } - } catch (err) { - util.destroy(this, err) - } - } - const onDrain = function () { - if (finished) { - return - } + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: - if (body.resume) { - body.resume() - } + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv } - const onAbort = function () { - if (finished) { - return - } - const err = new RequestAbortedError() - queueMicrotask(() => onFinished(err)) + + // 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) } - const onFinished = function (err) { - if (finished) { - return - } - finished = true + // 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() - assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + // 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) - socket - .off('drain', onDrain) - .off('error', onFinished) + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. - body - .removeListener('data', onData) - .removeListener('end', onFinished) - .removeListener('error', onFinished) - .removeListener('close', onAbort) + 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. - if (!err) { - try { - writer.end() - } catch (er) { - err = er - } - } + // 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) - writer.destroy(err) + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } - if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { - util.destroy(body, err) - } else { - util.destroy(body) + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) } - } - body - .on('data', onData) - .on('end', onFinished) - .on('error', onFinished) - .on('close', onAbort) + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) - if (body.resume) { - body.resume() - } + // 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). - socket - .on('drain', onDrain) - .on('error', onFinished) -} + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) -async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength === body.size, 'blob body must have content length') + // 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 - const isH2 = client[kHTTPConnVersion] === 'h2' - try { - if (contentLength != null && contentLength !== body.size) { - throw new RequestContentLengthMismatchError() - } + // 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. - const buffer = Buffer.from(await body.arrayBuffer()) + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue - 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() + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) } - request.onBodySent(buffer) - request.onRequestSent() + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() - if (!expectsPayload) { - socket[kReset] = true - } + // 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. - resume(client) - } catch (err) { - util.destroy(isH2 ? h2stream : socket, err) - } -} + // 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: -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() + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue } - } - const waitForDrain = () => new Promise((resolve, reject) => { - assert(callback === null) + // 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. - if (socket[kError]) { - reject(socket[kError]) - } else { - callback = resolve - } - }) + 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. - if (client[kHTTPConnVersion] === 'h2') { - h2stream - .on('close', onDrain) - .on('drain', onDrain) + 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: - 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] - } + // 1. Let enforcement be "Default". + let enforcement = 'Default' - 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) + 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' } - 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() - } + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' } - writer.end() - } catch (err) { - writer.destroy(err) - } finally { - socket - .off('close', onDrain) - .off('drain', onDrain) - } -} + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } -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 + // 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 ??= [] - socket[kWriting] = true + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) } - write (chunk) { - const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} - if (socket[kError]) { - throw socket[kError] - } +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} - 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() - } +/***/ 3834: +/***/ ((module) => { - process.emitWarning(new RequestContentLengthMismatchError()) - } - socket.cork() - if (bytesWritten === 0) { - if (!expectsPayload) { - socket[kReset] = true - } +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } - if (contentLength === null) { - socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') - } else { - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - } - } + for (const char of value) { + const code = char.charCodeAt(0) - if (contentLength === null) { - socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false } + } +} - this.bytesWritten += len - - const ret = socket.write(chunk) - - socket.uncork() - - request.onBodySent(chunk) +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) - 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() - } - } + 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') } - - return ret } +} - end () { - const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this - request.onRequestSent() - - socket[kWriting] = false - - if (socket[kError]) { - throw socket[kError] - } +/** + 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 (socket.destroyed) { - return + 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') } + } +} - 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. +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) - 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 (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') } + } +} - if (contentLength !== null && bytesWritten !== contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } else { - process.emitWarning(new RequestContentLengthMismatchError()) - } - } +/** + * 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') + } +} - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() - } - } +/** + * @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] - resume(client) - } + 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 - destroy (err) { - const { socket, client } = this + 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 - socket[kWriting] = false + GMT = %x47.4D.54 ; "GMT", case-sensitive - if (err) { - assert(client[kRunning] <= 1, 'pipeline should only contain this request') - util.destroy(socket, err) - } - } -} + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) -function errorRequest (client, request, err) { - try { - request.onError(err) - assert(request.aborted) - } catch (err) { - client.emit('error', err) + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) } -} -module.exports = Client + 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') -/***/ 3194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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 + } -/* istanbul ignore file: only for Node 12 */ + validateCookieName(cookie.name) + validateCookieValue(cookie.value) -const { kConnected, kSize } = __nccwpck_require__(6443) + const out = [`${cookie.name}=${cookie.value}`] -class CompatWeakRef { - constructor (value) { - this.value = 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 } - deref () { - return this.value[kConnected] === 0 && this.value[kSize] === 0 - ? undefined - : this.value + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' } -} -class CompatFinalizer { - constructor (finalizer) { - this.finalizer = finalizer + if (cookie.secure) { + out.push('Secure') } - register (dispatcher, key) { - if (dispatcher.on) { - dispatcher.on('disconnect', () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key) - } - }) - } + if (cookie.httpOnly) { + out.push('HttpOnly') } -} -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 - } + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) } - return { - WeakRef: global.WeakRef || CompatWeakRef, - FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + + 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)}`) + } -/***/ 9237: -/***/ ((module) => { + 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('=') -// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size -const maxAttributeValueSize = 1024 + out.push(`${key.trim()}=${value.join('=')}`) + } -// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size -const maxNameValuePairSize = 4096 + return out.join('; ') +} module.exports = { - maxAttributeValueSize, - maxNameValuePairSize + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify } /***/ }), -/***/ 3168: +/***/ 9136: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { parseSetCookie } = __nccwpck_require__(8915) -const { stringify } = __nccwpck_require__(3834) -const { webidl } = __nccwpck_require__(4222) -const { Headers } = __nccwpck_require__(6349) - -/** - * @typedef {Object} Cookie - * @property {string} name - * @property {string} value - * @property {Date|number|undefined} expires - * @property {number|undefined} maxAge - * @property {string|undefined} domain - * @property {string|undefined} path - * @property {boolean|undefined} secure - * @property {boolean|undefined} httpOnly - * @property {'Strict'|'Lax'|'None'} sameSite - * @property {string[]} unparsed - */ +const net = __nccwpck_require__(9278) +const assert = __nccwpck_require__(2613) +const util = __nccwpck_require__(3440) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) -/** - * @param {Headers} headers - * @returns {Record} - */ -function getCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) +let tls // include tls conditionally since it is not always available - webidl.brandCheck(headers, Headers, { strict: false }) +// 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. - const cookie = headers.get('cookie') - const out = {} +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 + } - if (!cookie) { - return out - } + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } - for (const piece of cookie.split(';')) { - const [name, ...value] = piece.split('=') + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } - out[name.trim()] = value.join('=') - } + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } - return out -} + 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() + } -/** - * @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' }) + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } - webidl.brandCheck(headers, Headers, { strict: false }) + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } - name = webidl.converters.DOMString(name) - attributes = webidl.converters.DeleteCookieAttributes(attributes) + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } - // Matches behavior of - // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 - setCookie(headers, { - name, - value: '', - expires: new Date(0), - ...attributes - }) + this._sessionCache.set(sessionKey, session) + } + } } -/** - * @param {Headers} headers - * @returns {Cookie[]} - */ -function getSetCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) +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') + } - webidl.brandCheck(headers, Headers, { strict: false }) + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = __nccwpck_require__(4756) + } + servername = servername || options.servername || util.getServerName(host) || null - const cookies = headers.getSetCookie() + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null - if (!cookies) { - return [] - } + assert(sessionKey) - return cookies.map((pair) => parseSetCookie(pair)) -} + 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 + }) -/** - * @param {Headers} headers - * @param {Cookie} cookie - * @returns {void} - */ -function setCookie (headers, cookie) { - webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) + 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 + }) + } - webidl.brandCheck(headers, Headers, { strict: false }) + // 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) + } - cookie = webidl.converters.Cookie(cookie) + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) - const str = stringify(cookie) + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() - if (str) { - headers.append('Set-Cookie', stringify(cookie)) + 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 } } -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 +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} } -]) -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) + 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() } - - 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: [] + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) } -]) +} -module.exports = { - getCookies, - deleteCookie, - getSetCookies, - setCookie +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) } +module.exports = buildConnector + /***/ }), -/***/ 8915: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 735: +/***/ ((module) => { -const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237) -const { isCTLExcludingHtab } = __nccwpck_require__(3834) -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322) -const assert = __nccwpck_require__(2613) +/** @type {Record} */ +const headerNameLowerCasedRecord = {} -/** - * @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 - } +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] - let nameValuePair = '' - let unparsedAttributes = '' - let name = '' - let value = '' +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} - // 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 } +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) - nameValuePair = collectASequenceOfCodePointsFast(';', header, position) - unparsedAttributes = header.slice(position.position) - } else { - // Otherwise: +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} - // 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() +/***/ 8707: +/***/ ((module) => { - // 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) + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' } } -/** - * 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 +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' } +} - // 2. Discard the first character of the unparsed-attributes (which - // will be a %x3B (";") character). - assert(unparsedAttributes[0] === ';') - unparsedAttributes = unparsedAttributes.slice(1) +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' + } +} - let cookieAv = '' +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' + } +} - // 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: +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' + } +} - // 1. Consume the remainder of the unparsed-attributes. - cookieAv = unparsedAttributes - unparsedAttributes = '' +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 } +} - // Let the cookie-av string be the characters consumed in this step. +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' + } +} - let attributeName = '' - let attributeValue = '' +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' + } +} - // 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 } +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' + } +} - attributeName = collectASequenceOfCodePointsFast( - '=', - cookieAv, - position - ) - attributeValue = cookieAv.slice(position.position + 1) - } else { - // Otherwise: +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' + } +} - // 1. The attribute-name string consists of the entire cookie-av - // string, and the attribute-value string is empty. - attributeName = cookieAv +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' } +} - // 5. Remove any leading or trailing WSP characters from the attribute- - // name string and the attribute-value string. - attributeName = attributeName.trim() - attributeValue = attributeValue.trim() +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' + } +} - // 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) +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' } +} - // 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() +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' + } +} - // 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) +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 + } +} - // 2. If the attribute-value failed to parse as a cookie date, ignore - // the cookie-av. +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' + } +} - 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. +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' + } +} - // 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) +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 + } +} - if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } +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' + } +} - // 2. If the remainder of attribute-value contains a non-DIGIT - // character, ignore the cookie-av. - if (!/^\d+$/.test(attributeValue)) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + Error.captureStackTrace(this, RequestRetryError) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } +} - // 3. Let delta-seconds be the attribute-value converted to an integer. - const deltaSeconds = Number(attributeValue) +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError +} - // 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 +/***/ 4655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) - } +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(8707) +const assert = __nccwpck_require__(2613) +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443) +const util = __nccwpck_require__(3440) - // 3. Convert the cookie-domain to lower case. - cookieDomain = cookieDomain.toLowerCase() +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js - // 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. +/** + * 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!#$%&'*+.|~]+$/ - // 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: +/** + * 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]/ - // 1. Let cookie-path be the attribute-value. - cookiePath = attributeValue - } +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ - // 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. +const kHandler = Symbol('handler') - 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. +const channels = {} - 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: +let extractBody - // 1. Let enforcement be "Default". - let enforcement = 'Default' +try { + const diagnosticsChannel = __nccwpck_require__(1637) + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} - 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' +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') } - // 3. If cookie-av's attribute-value is a case-insensitive match for - // "Strict", set enforcement to "Strict". - if (attributeValueLowercase.includes('strict')) { - enforcement = 'Strict' + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') } - // 4. If cookie-av's attribute-value is a case-insensitive match for - // "Lax", set enforcement to "Lax". - if (attributeValueLowercase.includes('lax')) { - enforcement = 'Lax' + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') } - // 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 ??= [] + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } - cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) - } + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } - // 8. Return to Step 1 of this algorithm. - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) -} + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } -module.exports = { - parseSetCookie, - parseUnparsedAttributes -} + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + this.headersTimeout = headersTimeout -/***/ }), + this.bodyTimeout = bodyTimeout -/***/ 3834: -/***/ ((module) => { + this.throwOnError = throwOnError === true + this.method = method + this.abort = null -/** - * @param {string} value - * @returns {boolean} - */ -function isCTLExcludingHtab (value) { - if (value.length === 0) { - return false - } + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body - for (const char of value) { - const code = char.charCodeAt(0) + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) + } + this.body.on('end', this.endHandler) + } - if ( - (code >= 0x00 || code <= 0x08) || - (code >= 0x0A || code <= 0x1F) || - code === 0x7F - ) { - return false + 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') } - } -} -/** - 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') - } - } -} + this.completed = false -/** - 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) + this.aborted = false - 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') - } - } -} + this.upgrade = upgrade || null -/** - * path-value = - * @param {string} path - */ -function validateCookiePath (path) { - for (const char of path) { - const code = char.charCodeAt(0) + this.path = query ? util.buildURL(path, query) : path - if (code < 0x21 || char === ';') { - throw new Error('Invalid cookie path') - } - } -} + this.origin = origin -/** - * 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') - } -} + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent -/** - * @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] + this.blocking = blocking == null ? false : blocking - 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 + this.reset = reset == null ? null : reset - 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 + this.host = null - GMT = %x47.4D.54 ; "GMT", case-sensitive + this.contentLength = null - time-of-day = hour ":" minute ":" second - ; 00:00:00 - 23:59:60 (leap second) + this.contentType = null - hour = 2DIGIT - minute = 2DIGIT - second = 2DIGIT - */ -function toIMFDate (date) { - if (typeof date === 'number') { - date = new Date(date) - } + this.headers = '' - const days = [ - 'Sun', 'Mon', 'Tue', 'Wed', - 'Thu', 'Fri', 'Sat' - ] + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false - const months = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' - ] + 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') + } - 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') + 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.') + } - return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` -} + if (!extractBody) { + extractBody = (__nccwpck_require__(8923).extractBody) + } -/** - 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') - } -} + 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` + } -/** - * @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 - } + util.validateHandler(handler, method, upgrade) - validateCookieName(cookie.name) - validateCookieValue(cookie.value) + this.servername = util.getServerName(this.host) - const out = [`${cookie.name}=${cookie.value}`] + this[kHandler] = handler - // 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 (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } } - if (cookie.name.startsWith('__Host-')) { - cookie.secure = true - cookie.domain = null - cookie.path = '/' + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } } - if (cookie.secure) { - out.push('Secure') - } + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } - if (cookie.httpOnly) { - out.push('HttpOnly') + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } } - if (typeof cookie.maxAge === 'number') { - validateCookieMaxAge(cookie.maxAge) - out.push(`Max-Age=${cookie.maxAge}`) - } + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) - if (cookie.domain) { - validateCookieDomain(cookie.domain) - out.push(`Domain=${cookie.domain}`) + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } } - if (cookie.path) { - validateCookiePath(cookie.path) - out.push(`Path=${cookie.path}`) - } + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) - if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { - out.push(`Expires=${toIMFDate(cookie.expires)}`) - } + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } - if (cookie.sameSite) { - out.push(`SameSite=${cookie.sameSite}`) + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } } - for (const part of cookie.unparsed) { - if (!part.includes('=')) { - throw new Error('Invalid unparsed') + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false } + } - const [key, ...value] = part.split('=') + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) - out.push(`${key.trim()}=${value.join('=')}`) + return this[kHandler].onUpgrade(statusCode, headers, socket) } - return out.join('; ') -} + onComplete (trailers) { + this.onFinally() -module.exports = { - isCTLExcludingHtab, - validateCookieName, - validateCookiePath, - validateCookieValue, - toIMFDate, - stringify -} + assert(!this.aborted) + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } -/***/ }), + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } -/***/ 9136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + onError (error) { + this.onFinally() + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + if (this.aborted) { + return + } + this.aborted = true -const net = __nccwpck_require__(9278) -const assert = __nccwpck_require__(2613) -const util = __nccwpck_require__(3440) -const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) + return this[kHandler].onError(error) + } -let tls // include tls conditionally since it is not always available + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } -// 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. + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } -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 - } + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this + } - const ref = this._sessionCache.get(key) - if (ref !== undefined && ref.deref() === undefined) { - this._sessionCache.delete(key) - } - }) - } + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } - get (sessionKey) { - const ref = this._sessionCache.get(sessionKey) - return ref ? ref.deref() : null - } + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } + const request = new Request(origin, opts, handler) - this._sessionCache.set(sessionKey, new WeakRef(session)) - this._sessionRegistry.register(session, sessionKey) + 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 } -} else { - SessionCache = class SimpleSessionCache { - constructor (maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions - this._sessionCache = new Map() - } - get (sessionKey) { - return this._sessionCache.get(sessionKey) - } + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } + for (const header of rawHeaders) { + const [key, value] = header.split(': ') - if (this._sessionCache.size >= this._maxCachedSessions) { - // remove the oldest session - const { value: oldestKey } = this._sessionCache.keys().next() - this._sessionCache.delete(oldestKey) - } + if (value == null || value.length === 0) continue - this._sessionCache.set(sessionKey, session) + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value } + + return headers } } -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') +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) } - const options = { path: socketPath, ...opts } - const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) - timeout = timeout == null ? 10e3 : timeout - allowH2 = allowH2 != null ? allowH2 : false - return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { - let socket - if (protocol === 'https:') { - if (!tls) { - tls = __nccwpck_require__(4756) - } - servername = servername || options.servername || util.getServerName(host) || null + val = val != null ? `${val}` : '' - const sessionKey = servername || hostname - const session = sessionCache.get(sessionKey) || null + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } - assert(sessionKey) + return skipAppend ? val : `${key}: ${val}\r\n` +} - 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 - }) +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 + } - 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 - }) + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) } - - // 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) + // 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) } + } +} - const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) +module.exports = Request - 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) - } - }) +/***/ 6443: +/***/ ((module) => { - return socket - } +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable') } -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) - } +/***/ }), + +/***/ 3440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const assert = __nccwpck_require__(2613) +const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443) +const { IncomingMessage } = __nccwpck_require__(8611) +const stream = __nccwpck_require__(2203) +const net = __nccwpck_require__(9278) +const { InvalidArgumentError } = __nccwpck_require__(8707) +const { Blob } = __nccwpck_require__(181) +const nodeUtil = __nccwpck_require__(9023) +const { stringify } = __nccwpck_require__(3480) +const { headerNameLowerCasedRecord } = __nccwpck_require__(735) + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' } -function onConnectTimeout (socket) { - util.destroy(socket, new ConnectTimeoutError()) +// 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]) + ) } -module.exports = buildConnector +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 + } -/***/ 735: -/***/ ((module) => { + 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:`.') + } -/** @type {Record} */ -const headerNameLowerCasedRecord = {} + return url + } -// https://developer.mozilla.org/docs/Web/HTTP/Headers -const wellknownHeaderNames = [ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -] + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey -} + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) + 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.') + } -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord -} + 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.') + } -/***/ 8707: -/***/ ((module) => { + 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) + } -class UndiciError extends Error { - constructor (message) { - super(message) - this.name = 'UndiciError' - this.code = 'UND_ERR' + 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) } -} -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' - } + return url } -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' +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') } + + return url } -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' +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) } -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' +// 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 } -} -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 + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' } + + return servername } -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' - } +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) } -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' - } +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') } -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' - } +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) } -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' +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 } -} -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' - } + return null } -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' - } +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) } -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 - } +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted } -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' +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return } -} -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' - } -} + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } -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 + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) } -} -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' + if (stream.destroyed !== true) { + stream[kDestroyed] = true } } -class RequestRetryError extends UndiciError { - constructor (message, code, { headers, data }) { - super(message) - Error.captureStackTrace(this, RequestRetryError) - this.name = 'RequestRetryError' - this.message = message || 'Request retry error' - this.code = 'UND_ERR_REQ_RETRY' - this.statusCode = code - this.data = data - this.headers = headers - } +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 } -module.exports = { - HTTPParserError, - UndiciError, - HeadersTimeoutError, - HeadersOverflowError, - BodyTimeoutError, - RequestContentLengthMismatchError, - ConnectTimeoutError, - ResponseStatusCodeError, - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError, - ClientDestroyedError, - ClientClosedError, - InformationalError, - SocketError, - NotSupportedError, - ResponseContentLengthMismatchError, - BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() } +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers -/***/ }), - -/***/ 4655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] -const { - InvalidArgumentError, - NotSupportedError -} = __nccwpck_require__(8707) -const assert = __nccwpck_require__(2613) -const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443) -const util = __nccwpck_require__(3440) + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1].map(x => x.toString('utf8')) + } else { + obj[key] = headers[i + 1].toString('utf8') + } + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } + } -// tokenRegExp and headerCharRegex have been lifted from -// https://github.com/nodejs/node/blob/main/lib/_http_common.js + // 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') + } -/** - * 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!#$%&'*+.|~]+$/ + return obj +} -/** - * 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]/ +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 -// Verifies that a given path is valid does not contain control chars \x00 to \x20 -const invalidPathRegex = /[^\u0021-\u00ff]/ + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') -const kHandler = Symbol('handler') + 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) + } + } -const channels = {} + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } -let extractBody + return ret +} -try { - const diagnosticsChannel = __nccwpck_require__(1637) - channels.create = diagnosticsChannel.channel('undici:request:create') - channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') - channels.headers = diagnosticsChannel.channel('undici:request:headers') - channels.trailers = diagnosticsChannel.channel('undici:request:trailers') - channels.error = diagnosticsChannel.channel('undici:request:error') -} catch { - channels.create = { hasSubscribers: false } - channels.bodySent = { hasSubscribers: false } - channels.headers = { hasSubscribers: false } - channels.trailers = { hasSubscribers: false } - channels.error = { hasSubscribers: false } +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) } -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') - } +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } - 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 (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } - if (upgrade && typeof upgrade !== 'string') { - throw new InvalidArgumentError('upgrade must be a string') - } + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('invalid headersTimeout') - } + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('invalid bodyTimeout') + 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 (reset != null && typeof reset !== 'boolean') { - throw new InvalidArgumentError('invalid reset') + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') } - if (expectContinue != null && typeof expectContinue !== 'boolean') { - throw new InvalidArgumentError('invalid expectContinue') + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') } + } +} - this.headersTimeout = headersTimeout +// 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) + )) +} - this.bodyTimeout = bodyTimeout +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} - this.throwOnError = throwOnError === true +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} - this.method = method +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 + } +} - this.abort = null +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} - if (body == null) { - this.body = null - } else if (util.isStream(body)) { - this.body = body +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } - const rState = this.body._readableState - if (!rState || !rState.autoDestroy) { - this.endHandler = function autoDestroy () { - util.destroy(this) - } - this.body.on('end', this.endHandler) - } + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } - this.errorHandler = err => { - if (this.abort) { - this.abort(err) + 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 { - this.error = err + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() } - 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 + }, + 0 + ) +} - this.upgrade = upgrade || null +// 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' + ) +} - this.path = query ? util.buildURL(path, query) : path +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 + } + } +} - this.origin = origin +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) +} - this.idempotent = idempotent == null - ? method === 'HEAD' || method === 'GET' - : idempotent +const hasToWellFormed = !!String.prototype.toWellFormed - this.blocking = blocking == null ? false : blocking +/** + * @param {string} val + */ +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } - this.reset = reset == null ? null : reset + return `${val}` +} - this.host = null +// Parsed accordingly to RFC 9110 +// https://www.rfc-editor.org/rfc/rfc9110#field.content-range +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } - this.contentLength = null + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} - this.contentType = null +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true - this.headers = '' +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + addAbortListener, + parseRangeHeader, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +} - // 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.') - } +/***/ 1: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!extractBody) { - extractBody = (__nccwpck_require__(8923).extractBody) - } - const [bodyStream, contentType] = extractBody(body) - if (this.contentType == null) { - this.contentType = contentType - this.headers += `content-type: ${contentType}\r\n` - } - this.body = bodyStream.stream - this.contentLength = bodyStream.length - } else if (util.isBlobLike(body) && this.contentType == null && body.type) { - this.contentType = body.type - this.headers += `content-type: ${body.type}\r\n` - } - util.validateHandler(handler, method, upgrade) +const Dispatcher = __nccwpck_require__(992) +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = __nccwpck_require__(8707) +const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443) - this.servername = util.getServerName(this.host) +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') - this[kHandler] = handler +class DispatcherBase extends Dispatcher { + constructor () { + super() - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }) - } + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] } - onBodySent (chunk) { - if (this[kHandler].onBodySent) { - try { - return this[kHandler].onBodySent(chunk) - } catch (err) { - this.abort(err) - } - } + get destroyed () { + return this[kDestroyed] } - onRequestSent () { - if (channels.bodySent.hasSubscribers) { - channels.bodySent.publish({ request: this }) - } + get closed () { + return this[kClosed] + } - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent() - } catch (err) { - this.abort(err) + 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') + } } } - } - onConnect (abort) { - assert(!this.aborted) - assert(!this.completed) + this[kInterceptors] = newInterceptors + } - if (this.error) { - abort(this.error) - } else { - this.abort = abort - return this[kHandler].onConnect(abort) + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) } - } - onHeaders (statusCode, headers, resume, statusText) { - assert(!this.aborted) - assert(!this.completed) + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return } - try { - return this[kHandler].onHeaders(statusCode, headers, resume, statusText) - } catch (err) { - this.abort(err) + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return } - } - onData (chunk) { - assert(!this.aborted) - assert(!this.completed) + this[kClosed] = true + this[kOnClosed].push(callback) - try { - return this[kHandler].onData(chunk) - } catch (err) { - this.abort(err) - return false + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } } - } - - onUpgrade (statusCode, headers, socket) { - assert(!this.aborted) - assert(!this.completed) - return this[kHandler].onUpgrade(statusCode, headers, socket) + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) } - onComplete (trailers) { - this.onFinally() - - assert(!this.aborted) - - this.completed = true - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers }) + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null } - try { - return this[kHandler].onComplete(trailers) - } catch (err) { - // TODO (fix): This might be a bad idea? - this.onError(err) + 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) + }) + }) } - } - onError (error) { - this.onFinally() - - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }) + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') } - if (this.aborted) { + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } return } - this.aborted = true - - return this[kHandler].onError(error) - } - onFinally () { - if (this.errorHandler) { - this.body.off('error', this.errorHandler) - this.errorHandler = null + if (!err) { + err = new ClientDestroyedError() } - if (this.endHandler) { - this.body.off('end', this.endHandler) - this.endHandler = null + 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) + } } - } - // TODO: adjust to support H2 - addHeader (key, value) { - processHeader(this, key, value) - return this + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) } - static [kHTTP1BuildRequest] (origin, opts, handler) { - // TODO: Migrate header parsing here, to make Requests - // HTTP agnostic - return new Request(origin, opts, handler) - } + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } - static [kHTTP2BuildRequest] (origin, opts, handler) { - const headers = opts.headers - opts = { ...opts, headers: null } + 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) + } - const request = new Request(origin, opts, handler) + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } - request.headers = {} + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError('headers array must be even') + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() } - for (let i = 0; i < headers.length; i += 2) { - processHeader(request, headers[i], headers[i + 1], true) + + if (this[kClosed]) { + throw new ClientClosedError() } - } 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) + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') } - } else if (headers != null) { - throw new InvalidArgumentError('headers must be an object or an array') - } - return request + handler.onError(err) + + return false + } } +} - static [kHTTP2CopyHeaders] (raw) { - const rawHeaders = raw.split('\r\n') - const headers = {} +module.exports = DispatcherBase - 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 - } +/***/ 992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return headers - } -} -function processHeaderValue (key, val, skipAppend) { - if (val && typeof val === 'object') { - throw new InvalidArgumentError(`invalid ${key} header`) - } - val = val != null ? `${val}` : '' +const EventEmitter = __nccwpck_require__(4434) - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') } - 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 + close () { + throw new Error('not implemented') } - 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) - } + destroy () { + throw new Error('not implemented') } } -module.exports = Request +module.exports = Dispatcher /***/ }), -/***/ 6443: -/***/ ((module) => { +/***/ 8923: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = { - kClose: Symbol('close'), - kDestroy: Symbol('destroy'), - kDispatch: Symbol('dispatch'), - kUrl: Symbol('url'), - kWriting: Symbol('writing'), - kResuming: Symbol('resuming'), - kQueue: Symbol('queue'), - kConnect: Symbol('connect'), - kConnecting: Symbol('connecting'), - kHeadersList: Symbol('headers list'), - kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), - kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), - kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), - kKeepAliveTimeoutValue: Symbol('keep alive timeout'), - kKeepAlive: Symbol('keep alive'), - kHeadersTimeout: Symbol('headers timeout'), - kBodyTimeout: Symbol('body timeout'), - kServerName: Symbol('server name'), - kLocalAddress: Symbol('local address'), - kHost: Symbol('host'), - kNoRef: Symbol('no ref'), - kBodyUsed: Symbol('used'), - kRunning: Symbol('running'), - kBlocking: Symbol('blocking'), - kPending: Symbol('pending'), - kSize: Symbol('size'), - kBusy: Symbol('busy'), - kQueued: Symbol('queued'), - kFree: Symbol('free'), - kConnected: Symbol('connected'), - kClosed: Symbol('closed'), - kNeedDrain: Symbol('need drain'), - kReset: Symbol('reset'), - kDestroyed: Symbol.for('nodejs.stream.destroyed'), - kMaxHeadersSize: Symbol('max headers size'), - kRunningIdx: Symbol('running index'), - kPendingIdx: Symbol('pending index'), - kError: Symbol('error'), - kClients: Symbol('clients'), - kClient: Symbol('client'), - kParser: Symbol('parser'), - kOnDestroyed: Symbol('destroy callbacks'), - kPipelining: Symbol('pipelining'), - kSocket: Symbol('socket'), - kHostHeader: Symbol('host header'), - kConnector: Symbol('connector'), - kStrictContentLength: Symbol('strict content length'), - kMaxRedirections: Symbol('maxRedirections'), - kMaxRequests: Symbol('maxRequestsPerClient'), - kProxy: Symbol('proxy agent options'), - kCounter: Symbol('socket request counter'), - kInterceptors: Symbol('dispatch interceptors'), - kMaxResponseSize: Symbol('max response size'), - kHTTP2Session: Symbol('http2Session'), - kHTTP2SessionState: Symbol('http2Session state'), - kHTTP2BuildRequest: Symbol('http2 build request'), - kHTTP1BuildRequest: Symbol('http1 build request'), - kHTTP2CopyHeaders: Symbol('http2 copy headers'), - kHTTPConnVersion: Symbol('http connection version'), - kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), - kConstruct: Symbol('constructable') + + +const Busboy = __nccwpck_require__(9581) +const util = __nccwpck_require__(3440) +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = __nccwpck_require__(5523) +const { FormData } = __nccwpck_require__(3073) +const { kState } = __nccwpck_require__(9710) +const { webidl } = __nccwpck_require__(4222) +const { DOMException, structuredClone } = __nccwpck_require__(7326) +const { Blob, File: NativeFile } = __nccwpck_require__(181) +const { kBodyUsed } = __nccwpck_require__(6443) +const assert = __nccwpck_require__(2613) +const { isErrored } = __nccwpck_require__(3440) +const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253) +const { File: UndiciFile } = __nccwpck_require__(3041) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) + +let random +try { + const crypto = __nccwpck_require__(7598) + random = (max) => crypto.randomInt(0, max) +} catch { + random = (max) => Math.floor(Math.random(max)) } +let ReadableStream = globalThis.ReadableStream -/***/ }), +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() -/***/ 3440: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } + // 1. Let stream be null. + let stream = null + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? textEncoder.encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } -const assert = __nccwpck_require__(2613) -const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443) -const { IncomingMessage } = __nccwpck_require__(8611) -const stream = __nccwpck_require__(2203) -const net = __nccwpck_require__(9278) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { Blob } = __nccwpck_require__(181) -const nodeUtil = __nccwpck_require__(9023) -const { stringify } = __nccwpck_require__(3480) -const { headerNameLowerCasedRecord } = __nccwpck_require__(735) + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) -const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + // 6. Let action be null. + let action = null -function nop () {} + // 7. Let source be null. + let source = null -function isStream (obj) { - return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' -} + // 8. Let length be null. + let length = null -// 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]) - ) -} + // 9. Let type be null. + let type = null -function buildURL (url, queryParams) { - if (url.includes('?') || url.includes('#')) { - throw new Error('Query params cannot be passed when url already contains "?" or "#".') - } + // 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 - const stringified = stringify(queryParams) + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams - if (stringified) { - url += '?' + stringified - } + // 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 - return url -} + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() -function parseURL (url) { - if (typeof url === 'string') { - url = new URL(url) + // 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 - if (!/^https?:/.test(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView - return url - } + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` - if (!url || typeof url !== 'object') { - throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') - } + /*! 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') - if (!/^https?:/.test(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } + // 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. - 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.') - } + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false - if (url.path != null && typeof url.path !== 'string') { - throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + 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 + } + } } - if (url.pathname != null && typeof url.pathname !== 'string') { - throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null } - if (url.hostname != null && typeof url.hostname !== 'string') { - throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') - } + // Set source to object. + source = object - if (url.origin != null && typeof url.origin !== 'string') { - throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } } - 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 || ''}` + // 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 - if (origin.endsWith('/')) { - origin = origin.substring(0, origin.length - 1) - } + // Set source to object. + source = object - 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) - } + // Set length to object’s size. + length = object.size - return url -} + // 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') + } -function parseOrigin (url) { - url = parseURL(url) + // 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' + ) + } - if (url.pathname !== '/' || url.search || url.hash) { - throw new InvalidArgumentError('invalid url') + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) } - return url -} - -function getHostname (host) { - if (host[0] === '[') { - const idx = host.indexOf(']') + // 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) + } - assert(idx !== -1) - return host.substring(1, idx) + // 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 + }) } - const idx = host.indexOf(':') - if (idx === -1) return host + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } - return host.substring(0, idx) + // 14. Return (body, type). + return [body, type] } -// 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 +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = (__nccwpck_require__(3774).ReadableStream) } - assert.strictEqual(typeof host, 'string') + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: - const servername = getHostname(host) - if (net.isIP(servername)) { - return '' + // 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.') } - return servername + // 2. Return the results of extracting object. + return extractBody(object, keepalive) } -function deepClone (obj) { - return JSON.parse(JSON.stringify(obj)) -} +function cloneBody (body) { + // To clone a body body, run these steps: -function isAsyncIterable (obj) { - return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') -} + // https://fetch.spec.whatwg.org/#concept-body-clone -function isIterable (obj) { - return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) -} + // 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() -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 - } + // 2. Set body’s stream to out1. + body.stream = out1 - return null + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } } -function isDestroyed (stream) { - return !stream || !!(stream.destroyed || stream[kDestroyed]) -} +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream -function isReadableAborted (stream) { - const state = stream && stream._readableState - return isDestroyed(stream) && state && !state.endEmitted -} + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } -function destroy (stream, err) { - if (stream == null || !isStream(stream) || isDestroyed(stream)) { - return - } + if (stream.locked) { + throw new TypeError('The stream is locked.') + } - if (typeof stream.destroy === 'function') { - if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { - // See: https://github.com/nodejs/node/pull/38505/files - stream.socket = null - } + // Compat. + stream[kBodyUsed] = true - stream.destroy(err) - } else if (err) { - process.nextTick((stream, err) => { - stream.emit('error', err) - }, stream, err) + yield * stream + } } +} - if (stream.destroyed !== true) { - stream[kDestroyed] = true +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') } } -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 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) -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return headerNameLowerCasedRecord[value] || value.toLowerCase() -} + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } -function parseHeaders (headers, obj = {}) { - // For H2 support - if (!Array.isArray(headers)) return headers + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, - for (let i = 0; i < headers.length; i += 2) { - const key = headers[i].toString().toLowerCase() - let val = obj[key] + 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) + }, - if (!val) { - if (Array.isArray(headers[i + 1])) { - obj[key] = headers[i + 1].map(x => x.toString('utf8')) - } else { - obj[key] = headers[i + 1].toString('utf8') - } - } else { - if (!Array.isArray(val)) { - val = [val] - obj[key] = val - } - val.push(headers[i + 1].toString('utf8')) - } - } + 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) + }, - // 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') - } + 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) + }, - return obj -} + async formData () { + webidl.brandCheck(this, instance) -function parseRawHeaders (headers) { - const ret = [] - let hasContentLength = false - let contentDispositionIdx = -1 + throwIfAborted(this[kState]) - for (let n = 0; n < headers.length; n += 2) { - const key = headers[n + 0].toString() - const val = headers[n + 1].toString('utf8') + const contentType = this.headers.get('Content-Type') - 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) - } - } + // 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 - // See https://github.com/nodejs/node/pull/46528 - if (hasContentLength && contentDispositionIdx !== -1) { - ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') - } + const responseFormData = new FormData() - return ret -} + let busboy -function isBuffer (buffer) { - // See, https://github.com/mcollina/undici/pull/319 - return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) -} + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } -function validateHandler (handler, method, upgrade) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] - if (typeof handler.onConnect !== 'function') { - throw new InvalidArgumentError('invalid onConnect method') - } + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') - if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { - throw new InvalidArgumentError('invalid onBodySent method') - } + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) - 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') - } + 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 })) + }) + } + }) - if (typeof handler.onData !== 'function') { - throw new InvalidArgumentError('invalid onData method') - } + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) - if (typeof handler.onComplete !== 'function') { - throw new InvalidArgumentError('invalid onComplete method') + 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.' + }) + } } } -} -// 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) - )) + return methods } -function isErrored (body) { - return !!(body && ( - stream.isErrored - ? stream.isErrored(body) - : /state: 'errored'/.test(nodeUtil.inspect(body) - ))) +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) } -function isReadable (body) { - return !!(body && ( - stream.isReadable - ? stream.isReadable(body) - : /state: 'readable'/.test(nodeUtil.inspect(body) - ))) -} +/** + * @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) -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 - } -} + throwIfAborted(object[kState]) -async function * convertIterableToBuffer (iterable) { - for await (const chunk of iterable) { - yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') } -} -let ReadableStream -function ReadableStreamFrom (iterable) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) + // 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) + } } - if (ReadableStream.from) { - return ReadableStream.from(convertIterableToBuffer(iterable)) + // 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 } - 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 - ) + // 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 } -// 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' - ) +// 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)) } -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 - } +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' } -} -function addAbortListener (signal, listener) { - if ('addEventListener' in signal) { - signal.addEventListener('abort', listener, { once: true }) - return () => signal.removeEventListener('abort', listener) + // 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) } - signal.addListener('abort', listener) - return () => signal.removeListener('abort', listener) -} -const hasToWellFormed = !!String.prototype.toWellFormed + // 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 +} /** - * @param {string} val + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes */ -function toUSVString (val) { - if (hasToWellFormed) { - return `${val}`.toWellFormed() - } else if (nodeUtil.toUSVString) { - return nodeUtil.toUSVString(val) - } - - return `${val}` +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) } -// Parsed accordingly to RFC 9110 -// https://www.rfc-editor.org/rfc/rfc9110#field.content-range -function parseRangeHeader (range) { - if (range == null || range === '') return { start: 0, end: null, size: null } +/** + * @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') - const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null - return m - ? { - start: parseInt(m[1]), - end: m[2] ? parseInt(m[2]) : null, - size: m[3] ? parseInt(m[3]) : null - } - : null -} + if (contentType === null) { + return 'failure' + } -const kEnumerableProperty = Object.create(null) -kEnumerableProperty.enumerable = true + return parseMIMEType(contentType) +} module.exports = { - kEnumerableProperty, - nop, - isDisturbed, - isErrored, - isReadable, - toUSVString, - isReadableAborted, - isBlobLike, - parseOrigin, - parseURL, - getServerName, - isStream, - isIterable, - isAsyncIterable, - isDestroyed, - headerNameToString, - parseRawHeaders, - parseHeaders, - parseKeepAliveTimeout, - destroy, - bodyLength, - deepClone, - ReadableStreamFrom, - isBuffer, - validateHandler, - getSocketInfo, - isFormDataLike, - buildURL, - throwIfAborted, - addAbortListener, - parseRangeHeader, - nodeMajor, - nodeMinor, - nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), - safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] + extractBody, + safelyExtractBody, + cloneBody, + mixinBody } /***/ }), -/***/ 1: +/***/ 7326: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const Dispatcher = __nccwpck_require__(992) -const { - ClientDestroyedError, - ClientClosedError, - InvalidArgumentError -} = __nccwpck_require__(8707) -const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443) - -const kDestroyed = Symbol('destroyed') -const kClosed = Symbol('closed') -const kOnDestroyed = Symbol('onDestroyed') -const kOnClosed = Symbol('onClosed') -const kInterceptedDispatch = Symbol('Intercepted Dispatch') - -class DispatcherBase extends Dispatcher { - constructor () { - super() +const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167) - this[kDestroyed] = false - this[kOnDestroyed] = null - this[kClosed] = false - this[kOnClosed] = [] - } +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) - get destroyed () { - return this[kDestroyed] - } +const nullBodyStatus = [101, 204, 205, 304] - get closed () { - return this[kClosed] - } +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) - get interceptors () { - return this[kInterceptors] - } +// 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' +] - 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') - } - } - } +const badPortsSet = new Set(badPorts) - this[kInterceptors] = newInterceptors - } +// 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) - close (callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - this.close((err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } +const requestRedirect = ['follow', 'manual', 'error'] - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) - if (this[kDestroyed]) { - queueMicrotask(() => callback(new ClientDestroyedError(), null)) - return - } +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] - if (this[kClosed]) { - if (this[kOnClosed]) { - this[kOnClosed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } +const requestCredentials = ['omit', 'same-origin', 'include'] - this[kClosed] = true - this[kOnClosed].push(callback) +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] - const onClosed = () => { - const callbacks = this[kOnClosed] - this[kOnClosed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } +// 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' +] - // Should not error. - this[kClose]() - .then(() => this.destroy()) - .then(() => { - queueMicrotask(onClosed) - }) +// 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 } +})() - destroy (err, callback) { - if (typeof err === 'function') { - callback = err - err = null - } +let channel - 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) - }) - }) +/** @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 (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') + if (!channel) { + channel = new MessageChannel() } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } - if (this[kDestroyed]) { - if (this[kOnDestroyed]) { - this[kOnDestroyed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } +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 +} - 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) - } - } +/***/ 4322: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Should not error. - this[kDestroy](err).then(() => { - queueMicrotask(onDestroyed) - }) - } +const assert = __nccwpck_require__(2613) +const { atob } = __nccwpck_require__(181) +const { isomorphicDecode } = __nccwpck_require__(5523) - [kInterceptedDispatch] (opts, handler) { - if (!this[kInterceptors] || this[kInterceptors].length === 0) { - this[kInterceptedDispatch] = this[kDispatch] - return this[kDispatch](opts, handler) - } +const encoder = new TextEncoder() - 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) - } +/** + * @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 - dispatch (opts, handler) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } +// 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:') - try { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('opts must be an object.') - } + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) - if (this[kDestroyed] || this[kOnDestroyed]) { - throw new ClientDestroyedError() - } + // 3. Remove the leading "data:" string from input. + input = input.slice(5) - if (this[kClosed]) { - throw new ClientClosedError() - } + // 4. Let position point at the start of input. + const position = { position: 0 } - return this[kInterceptedDispatch](opts, handler) - } catch (err) { - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } + // 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 + ) - handler.onError(err) + // 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) - return false - } + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' } -} -module.exports = DispatcherBase + // 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) -/***/ 992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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' + } -const EventEmitter = __nccwpck_require__(4434) + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) -class Dispatcher extends EventEmitter { - dispatch () { - throw new Error('not implemented') - } + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') - close () { - throw new Error('not implemented') + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) } - destroy () { - throw new Error('not implemented') + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType } -} - -module.exports = Dispatcher + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) -/***/ }), - -/***/ 8923: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } -const Busboy = __nccwpck_require__(9581) -const util = __nccwpck_require__(3440) -const { - ReadableStreamFrom, - isBlobLike, - isReadableStreamLike, - readableStreamClose, - createDeferredPromise, - fullyReadBody -} = __nccwpck_require__(5523) -const { FormData } = __nccwpck_require__(3073) -const { kState } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { DOMException, structuredClone } = __nccwpck_require__(7326) -const { Blob, File: NativeFile } = __nccwpck_require__(181) -const { kBodyUsed } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { isErrored } = __nccwpck_require__(3440) -const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253) -const { File: UndiciFile } = __nccwpck_require__(3041) -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) + const href = url.href + const hashLength = url.hash.length -let random -try { - const crypto = __nccwpck_require__(7598) - random = (max) => crypto.randomInt(0, max) -} catch { - random = (max) => Math.floor(Math.random(max)) + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) } -let ReadableStream = globalThis.ReadableStream +// 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 = '' -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile -const textEncoder = new TextEncoder() -const textDecoder = new TextDecoder() + // 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] -// https://fetch.spec.whatwg.org/#concept-bodyinit-extract -function extractBody (object, keepalive = false) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) + // 2. Advance position by 1. + position.position++ } - // 1. Let stream be null. - let stream = null + // 3. Return result. + return result +} - // 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 - }) +/** + * 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) } - // 5. Assert: stream is a ReadableStream object. - assert(isReadableStreamLike(stream)) + position.position = idx + return input.slice(start, position.position) +} - // 6. Let action be null. - let action = null +// 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) - // 7. Let source be null. - let source = null + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} - // 8. Let length be null. - let length = null +// 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 = [] - // 9. Let type be null. - let type = null + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] - // 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 + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) - // Set type to `text/plain;charset=UTF-8`. - type = 'text/plain;charset=UTF-8' - } else if (object instanceof URLSearchParams) { - // URLSearchParams + // 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) - // 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 + // 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) - // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. - source = object.toString() + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) - // 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 + // 3. Skip the next two bytes in input. + i += 2 + } + } - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.slice()) - } else if (ArrayBuffer.isView(object)) { - // BufferSource/ArrayBufferView + // 3. Return output. + return Uint8Array.from(output) +} - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) - } else if (util.isFormDataLike(object)) { - const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` - const prefix = `--${boundary}\r\nContent-Disposition: form-data` +// 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) - /*! 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') + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } - // 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. + // 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 + ) - const blobParts = [] - const rn = new Uint8Array([13, 10]) // '\r\n' - length = 0 - let hasUnknownSizeValue = false + // 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' + } - 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 - } - } - } + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } - const chunk = textEncoder.encode(`--${boundary}--`) - blobParts.push(chunk) - length += chunk.byteLength - if (hasUnknownSizeValue) { - length = null - } + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ - // Set source to object. - source = object + // 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 + ) - action = async function * () { - for (const part of blobParts) { - if (part.stream) { - yield * part.stream() - } else { - yield part - } - } - } + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) - // 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 + // 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' + } - // Set source to object. - source = object + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() - // Set length to object’s size. - length = object.size + // 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}` + } - // If object’s type attribute is not the empty byte sequence, set - // type to its value. - if (object.type) { - type = object.type + // 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++ } - } else if (typeof object[Symbol.asyncIterator] === 'function') { - // If keepalive is true, then throw a TypeError. - if (keepalive) { - throw new TypeError('keepalive') + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break } - // 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' + // 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 + } } - stream = - object instanceof ReadableStream ? object : ReadableStreamFrom(object) + // 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) + } } - // 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. Return mimeType. + return mimeType +} - // 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 - }) - } +// 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 - // 13. Let body be a body whose stream is stream, source is source, - // and length is length. - const body = { stream, source, length } + // 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(/=?=$/, '') + } - // 14. Return (body, type). - return [body, type] -} + // 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' + } -// https://fetch.spec.whatwg.org/#bodyinit-safely-extract -function safelyExtractBody (object, keepalive = false) { - if (!ReadableStream) { - // istanbul ignore next - ReadableStream = (__nccwpck_require__(3774).ReadableStream) + // 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' } - // To safely extract a body and a `Content-Type` value from - // a byte sequence or BodyInit object object, run these steps: + const binary = atob(data) + const bytes = new Uint8Array(binary.length) - // 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.') + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) } - // 2. Return the results of extracting object. - return extractBody(object, keepalive) + return bytes } -function cloneBody (body) { - // To clone a body body, run these steps: +// 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 - // https://fetch.spec.whatwg.org/#concept-body-clone + // 2. Let value be the empty string. + let value = '' - // 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() + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') - // 2. Set body’s stream to out1. - body.stream = out1 + // 4. Advance position by 1. + position.position++ - // 3. Return a body whose stream is out2 and other members are copied from body. - return { - stream: finalClone, - length: body.length, - source: body.source - } -} + // 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 + ) -async function * consumeBody (body) { - if (body) { - if (isUint8Array(body)) { - yield body - } else { - const stream = body.stream + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } - if (util.isDisturbed(stream)) { - throw new TypeError('The body has already been consumed.') - } + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] - if (stream.locked) { - throw new TypeError('The stream is locked.') + // 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 } - // Compat. - stream[kBodyUsed] = true + // 2. Append the code point at position within input to value. + value += input[position.position] - yield * stream + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break } } -} -function throwIfAborted (state) { - if (state.aborted) { - throw new DOMException('The operation was aborted.', 'AbortError') + // 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) } -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) +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType - if (mimeType === 'failure') { - mimeType = '' - } else if (mimeType) { - mimeType = serializeAMimeType(mimeType) - } + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence - // Return a Blob whose contents are bytes and type attribute - // is mimeType. - return new Blob([bytes], { type: mimeType }) - }, instance) - }, + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' - 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) - }, + // 2. Append name to serialization. + serialization += name - 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) - }, + // 3. Append U+003D (=) to serialization. + serialization += '=' - 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) - }, + // 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') - async formData () { - webidl.brandCheck(this, instance) + // 2. Prepend U+0022 (") to value. + value = '"' + value - throwIfAborted(this[kState]) + // 3. Append U+0022 (") to value. + value += '"' + } - const contentType = this.headers.get('Content-Type') + // 5. Append value to serialization. + serialization += value + } - // 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 + // 3. Return serialization. + return serialization +} - const responseFormData = new FormData() +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} - let busboy +/** + * @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 - try { - busboy = new Busboy({ - headers, - preservePath: true - }) - } catch (err) { - throw new DOMException(`${err}`, 'AbortError') - } + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + } - busboy.on('field', (name, value) => { - responseFormData.append(name, value) - }) - busboy.on('file', (name, value, filename, encoding, mimeType) => { - const chunks = [] + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } - if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { - let base64chunk = '' + return str.slice(lead, trail + 1) +} - value.on('data', (chunk) => { - base64chunk += chunk.toString().replace(/[\r\n]/gm, '') +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} - const end = base64chunk.length - base64chunk.length % 4 - chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) +/** + * @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 - 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 })) - }) - } - }) + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } - const busboyResolve = new Promise((resolve, reject) => { - busboy.on('finish', resolve) - busboy.on('error', (err) => reject(new TypeError(err))) - }) + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } - if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) - busboy.end() - await busboyResolve + return str.slice(lead, trail + 1) +} - return responseFormData - } else if (/application\/x-www-form-urlencoded/.test(contentType)) { - // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} - // 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() +/***/ 3041: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - throwIfAborted(this[kState]) - // Otherwise, throw a TypeError. - throw webidl.errors.exception({ - header: `${instance.name}.formData`, - message: 'Could not parse content as FormData.' - }) - } - } - } - return methods -} +const { Blob, File: NativeFile } = __nccwpck_require__(181) +const { types } = __nccwpck_require__(9023) +const { kState } = __nccwpck_require__(9710) +const { isBlobLike } = __nccwpck_require__(5523) +const { webidl } = __nccwpck_require__(4222) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) +const { kEnumerableProperty } = __nccwpck_require__(3440) +const encoder = new TextEncoder() -function mixinBody (prototype) { - Object.assign(prototype.prototype, bodyMixinMethods(prototype)) -} +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' }) -/** - * @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) + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) - throwIfAborted(object[kState]) + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us - // 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 n be the fileName argument to the constructor. + const n = fileName - // 2. Let promise be a new promise. - const promise = createDeferredPromise() + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: - // 3. Let errorSteps given error be to reject promise with error. - const errorSteps = (error) => promise.reject(error) + // 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 - // 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) - } - } + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) - // 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 - } + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } - // 6. Otherwise, fully read object’s body given successSteps, - // errorSteps, and object’s relevant global object. - await fullyReadBody(object[kState].body, successSteps, errorSteps) + t = serializeAMimeType(t).toLowerCase() + } - // 7. Return promise. - return promise.promise -} + // 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 + } -// 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)) -} + // 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. -/** - * @see https://encoding.spec.whatwg.org/#utf-8-decode - * @param {Buffer} buffer - */ -function utf8DecodeBytes (buffer) { - if (buffer.length === 0) { - return '' + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t + } } - // 1. Let buffer be the result of peeking three bytes from - // ioQueue, converted to a byte sequence. + get name () { + webidl.brandCheck(this, File) - // 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) + return this[kState].name } - // 3. Process a queue with an instance of UTF-8’s - // decoder, ioQueue, output, and "replacement". - const output = textDecoder.decode(buffer) + get lastModified () { + webidl.brandCheck(this, File) - // 4. Return output. - return output -} + return this[kState].lastModified + } -/** - * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value - * @param {Uint8Array} bytes - */ -function parseJSONFromBytes (bytes) { - return JSON.parse(utf8DecodeBytes(bytes)) + get type () { + webidl.brandCheck(this, File) + + return this[kState].type + } } -/** - * @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') +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check - if (contentType === null) { - return 'failure' - } + // 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: - return parseMIMEType(contentType) -} + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. -module.exports = { - extractBody, - safelyExtractBody, - cloneBody, - mixinBody -} + // 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 -/***/ 7326: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 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. -const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167) + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } -const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] -const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + stream (...args) { + webidl.brandCheck(this, FileLike) -const nullBodyStatus = [101, 204, 205, 304] + return this[kState].blobLike.stream(...args) + } -const redirectStatus = [301, 302, 303, 307, 308] -const redirectStatusSet = new Set(redirectStatus) + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) -// 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' -] + return this[kState].blobLike.arrayBuffer(...args) + } -const badPortsSet = new Set(badPorts) + slice (...args) { + webidl.brandCheck(this, FileLike) -// 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) + return this[kState].blobLike.slice(...args) + } -const requestRedirect = ['follow', 'manual', 'error'] + text (...args) { + webidl.brandCheck(this, FileLike) -const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -const safeMethodsSet = new Set(safeMethods) + return this[kState].blobLike.text(...args) + } -const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + get size () { + webidl.brandCheck(this, FileLike) -const requestCredentials = ['omit', 'same-origin', 'include'] + return this[kState].blobLike.size + } -const requestCache = [ - 'default', - 'no-store', - 'reload', - 'no-cache', - 'force-cache', - 'only-if-cached' -] + get type () { + webidl.brandCheck(this, FileLike) -// 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' -] + return this[kState].blobLike.type + } -// https://fetch.spec.whatwg.org/#enumdef-requestduplex -const requestDuplex = [ - 'half' -] + get name () { + webidl.brandCheck(this, FileLike) -// http://fetch.spec.whatwg.org/#forbidden-method -const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] -const forbiddenMethodsSet = new Set(forbiddenMethods) + return this[kState].name + } -const subresource = [ - 'audio', - 'audioworklet', - 'font', - 'image', - 'manifest', - 'paintworklet', - 'script', - 'style', - 'track', - 'video', - 'xslt', - '' -] -const subresourceSet = new Set(subresource) + get lastModified () { + webidl.brandCheck(this, FileLike) -/** @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 + return this[kState].lastModified } -})() -let channel + get [Symbol.toStringTag] () { + return 'File' + } +} -/** @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') +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 (!channel) { - channel = new MessageChannel() + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) } - 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 + 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() -/***/ 4322: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (value !== 'native') { + value = 'transparent' + } -const assert = __nccwpck_require__(2613) -const { atob } = __nccwpck_require__(181) -const { isomorphicDecode } = __nccwpck_require__(5523) + return value + }, + defaultValue: 'transparent' + } +]) -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 + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options */ -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:') +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] - // 2. Let input be the result of running the URL - // serializer on dataURL with exclude fragment - // set to true. - let input = URLSerializer(dataURL, true) + // 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 - // 3. Remove the leading "data:" string from input. - input = input.slice(5) + // 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) + } - // 4. Let position point at the start of input. - const position = { position: 0 } + // 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) + } + } - // 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 - ) + // 3. Return bytes. + return bytes +} - // 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) +/** + * @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' - // 7. If position is past the end of input, then - // return failure - if (position.position >= input.length) { - return 'failure' + // 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' } - // 8. Advance position by 1. - position.position++ + return s.replace(/\r?\n/g, nativeLineEnding) +} - // 9. Let encodedBody be the remainder of input. - const encodedBody = input.slice(mimeTypeLength + 1) +// 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' + ) + ) +} - // 10. Let body be the percent-decoding of encodedBody. - let body = stringPercentDecode(encodedBody) +module.exports = { File, FileLike, isFileLike } - // 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' - } +/***/ 3073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) - } +const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523) +const { kState } = __nccwpck_require__(9710) +const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041) +const { webidl } = __nccwpck_require__(4222) +const { Blob, File: NativeFile } = __nccwpck_require__(181) - // 12. If mimeType starts with U+003B (;), then prepend - // "text/plain" to mimeType. - if (mimeType.startsWith(';')) { - mimeType = 'text/plain' + mimeType - } +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile - // 13. Let mimeTypeRecord be the result of parsing - // mimeType. - let mimeTypeRecord = parseMIMEType(mimeType) +// 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'] + }) + } - // 14. If mimeTypeRecord is failure, then set - // mimeTypeRecord to text/plain;charset=US-ASCII. - if (mimeTypeRecord === 'failure') { - mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + this[kState] = [] } - // 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 } -} + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) -// https://url.spec.whatwg.org/#concept-url-serializer -/** - * @param {URL} url - * @param {boolean} excludeFragment - */ -function URLSerializer (url, excludeFragment = false) { - if (!excludeFragment) { - return url.href - } + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) - const href = url.href - const hashLength = url.hash.length + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } - return hashLength === 0 ? href : href.substring(0, href.length - hashLength) -} + // 1. Let value be value if given; otherwise blobValue. -// 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 = '' + 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. 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. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) - // 2. Advance position by 1. - position.position++ + // 3. Append entry to this’s entry list. + this[kState].push(entry) } - // 3. Return result. - return result -} + delete (name) { + webidl.brandCheck(this, FormData) -/** - * 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 + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) - if (idx === -1) { - position.position = input.length - return input.slice(start) - } + name = webidl.converters.USVString(name) - position.position = idx - return input.slice(start, position.position) -} + // 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) + } -// 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) + get (name) { + webidl.brandCheck(this, FormData) - // 2. Return the percent-decoding of bytes. - return percentDecode(bytes) -} + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) -// 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 = [] + name = webidl.converters.USVString(name) - // 2. For each byte byte in input: - for (let i = 0; i < input.length; i++) { - const byte = input[i] + // 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 + } - // 1. If byte is not 0x25 (%), then append byte to output. - if (byte !== 0x25) { - output.push(byte) + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } - // 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) + getAll (name) { + webidl.brandCheck(this, FormData) - // 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) + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) - // 2. Append a byte whose value is bytePoint to output. - output.push(bytePoint) + name = webidl.converters.USVString(name) - // 3. Skip the next two bytes in input. - i += 2 - } + // 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) } - // 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) + has (name) { + webidl.brandCheck(this, FormData) - // 2. Let position be a position variable for input, - // initially pointing at the start of input. - const position = { position: 0 } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) - // 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 - ) + name = webidl.converters.USVString(name) - // 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' + // 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 } - // 5. If position is past the end of input, then return - // failure - if (position.position > input.length) { - return 'failure' - } + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) - // 6. Advance position by 1. (This skips past U+002F (/).) - position.position++ + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) - // 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 - ) + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } - // 8. Remove any trailing HTTP whitespace from subtype. - subtype = removeHTTPWhitespace(subtype, false, true) + // The set(name, value) and set(name, blobValue, filename) method steps + // are: - // 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' + // 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) + } } - const typeLowercase = type.toLowerCase() - const subtypeLowercase = subtype.toLowerCase() + entries () { + webidl.brandCheck(this, FormData) - // 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}` + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) } - // 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++ + keys () { + webidl.brandCheck(this, FormData) - // 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 + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' ) + } - // 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 + values () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' ) + } - // 4. Set parameterName to parameterName, in ASCII - // lowercase. - parameterName = parameterName.toLowerCase() + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) - // 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 - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) - // 2. Advance position by 1. (This skips past U+003D (=).) - position.position++ + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) } - // 6. If position is past the end of input, then break. - if (position.position > input.length) { - break + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) } + } +} - // 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) +FormData.prototype[Symbol.iterator] = FormData.prototype.entries - // 2. Collect a sequence of code points that are not - // U+003B (;) from input, given position. - collectASequenceOfCodePointsFast( - ';', - input, - position - ) +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) - // 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 - ) +/** + * @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. Remove any trailing HTTP whitespace from parameterValue. - parameterValue = removeHTTPWhitespace(parameterValue, false, true) + // 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: - // 3. If parameterValue is the empty string, then continue. - if (parameterValue.length === 0) { - continue - } + // 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 }) } - // 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) + // 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) } } - // 12. Return mimeType. - return mimeType + // 4. Return an entry whose name is name and whose value is value. + return { name, value } } -// 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 +module.exports = { FormData } - // 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' - } +/***/ 5628: +/***/ ((module) => { - 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 +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] } -// 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 +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) - // 2. Let value be the empty string. - let value = '' + return + } - // 3. Assert: the code point at position within input - // is U+0022 ("). - assert(input[position.position] === '"') + const parsedURL = new URL(newOrigin) - // 4. Advance position by 1. - position.position++ + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } - // 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 - ) + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} - // 2. If position is past the end of input, then break. - if (position.position >= input.length) { - break - } +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} - // 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 - } +/***/ 6349: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 2. Append the code point at position within input to value. - value += input[position.position] +// https://github.com/Ethan-Arrowood/undici-fetch - // 3. Advance position by 1. - position.position++ - // 6. Otherwise: - } else { - // 1. Assert: quoteOrBackslash is U+0022 ("). - assert(quoteOrBackslash === '"') - // 2. Break. - break - } - } +const { kHeadersList, kConstruct } = __nccwpck_require__(6443) +const { kGuard } = __nccwpck_require__(9710) +const { kEnumerableProperty } = __nccwpck_require__(3440) +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = __nccwpck_require__(5523) +const util = __nccwpck_require__(9023) +const { webidl } = __nccwpck_require__(4222) +const assert = __nccwpck_require__(2613) - // 6. If the extract-value flag is set, then return value. - if (extractValue) { - return value - } +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') - // 7. Return the code points from positionStart to position, - // inclusive, within input. - return input.slice(positionStart, position.position) +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 } /** - * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue */ -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 += ';' +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length - // 2. Append name to serialization. - serialization += name + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i - // 3. Append U+003D (=) to serialization. - serialization += '=' + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} - // 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') +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: - // 2. Prepend U+0022 (") to value. - value = '"' + value + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } - // 3. Append U+0022 (") to value. - value += '"' + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw - // 5. Append value to serialization. - serialization += value + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) } - - // 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 + * @see https://fetch.spec.whatwg.org/#concept-headers-append */ -function removeHTTPWhitespace (str, leading = true, trailing = true) { - let lead = 0 - let trail = str.length - 1 +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) - if (leading) { - for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + // 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' + }) } - if (trailing) { - for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (headers[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (headers[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO } - return str.slice(lead, trail + 1) -} + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. -/** - * @see https://infra.spec.whatwg.org/#ascii-whitespace - * @param {string} char - */ -function isASCIIWhitespace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' + // 7. Append (name, value) to headers’s header list. + return headers[kHeadersList].append(name, value) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers } -/** - * @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 +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null - if (leading) { - for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } } - if (trailing) { - for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + // 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) } - return str.slice(lead, trail + 1) -} + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } -module.exports = { - dataURLProcessor, - URLSerializer, - collectASequenceOfCodePoints, - collectASequenceOfCodePointsFast, - stringPercentDecode, - parseMIMEType, - collectAnHTTPQuotedString, - serializeAMimeType -} + // 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 }) + } -/***/ 3041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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] + } -const { Blob, File: NativeFile } = __nccwpck_require__(181) -const { types } = __nccwpck_require__(9023) -const { kState } = __nccwpck_require__(9710) -const { isBlobLike } = __nccwpck_require__(5523) -const { webidl } = __nccwpck_require__(4222) -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const encoder = new TextEncoder() + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }) + } -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' }) + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null - fileBits = webidl.converters['sequence'](fileBits) - fileName = webidl.converters.USVString(fileName) - options = webidl.converters.FilePropertyBag(options) + name = name.toLowerCase() - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - // Note: Blob handles this for us + if (name === 'set-cookie') { + this.cookies = null + } - // 2. Let n be the fileName argument to the constructor. - const n = fileName + this[kHeadersMap].delete(name) + } - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + const value = this[kHeadersMap].get(name.toLowerCase()) - // 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 + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return value === undefined ? null : value.value + } - // eslint-disable-next-line no-labels - substep: { - if (t) { - t = parseMIMEType(t) + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } + } - if (t === 'failure') { - t = '' - // eslint-disable-next-line no-labels - break substep - } + get entries () { + const headers = {} - t = serializeAMimeType(t).toLowerCase() + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value } - - // 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. + return headers + } +} - super(processBlobParts(fileBits, options), { type: t }) - this[kState] = { - name: n, - lastModified: d, - type: t +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + if (init === kConstruct) { + return } - } + this[kHeadersList] = new HeadersList() - get name () { - webidl.brandCheck(this, File) + // The new Headers(init) constructor steps are: - return this[kState].name + // 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) + } } - get lastModified () { - webidl.brandCheck(this, File) + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) - return this[kState].lastModified - } + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) - get type () { - webidl.brandCheck(this, File) + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - return this[kState].type + return appendHeader(this, name, value) } -} -class FileLike { - constructor (blobLike, fileName, options = {}) { - // TODO: argument idl type check + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) - // 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, 1, { header: 'Headers.delete' }) - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. + name = webidl.converters.ByteString(name) - // 2. Let n be the fileName argument to the constructor. - const n = fileName + // 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' + }) + } - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: + // 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 + } - // 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 + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } - // 2. Convert every character in t to ASCII lowercase. - // TODO + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this[kHeadersList].delete(name) + } - // 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() + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) - // 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. + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) - this[kState] = { - blobLike, - name: n, - type: t, - lastModified: d - } - } + name = webidl.converters.ByteString(name) - stream (...args) { - webidl.brandCheck(this, FileLike) + // 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' + }) + } - return this[kState].blobLike.stream(...args) + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) } - arrayBuffer (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.arrayBuffer(...args) - } + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) - slice (...args) { - webidl.brandCheck(this, FileLike) + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) - return this[kState].blobLike.slice(...args) - } + name = webidl.converters.ByteString(name) - text (...args) { - webidl.brandCheck(this, FileLike) + // 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' + }) + } - return this[kState].blobLike.text(...args) + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) } - get size () { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.size - } + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) - get type () { - webidl.brandCheck(this, FileLike) + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) - return this[kState].blobLike.type - } + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) - get name () { - webidl.brandCheck(this, FileLike) + // 1. Normalize value. + value = headerValueNormalize(value) - return this[kState].name - } + // 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' + }) + } - get lastModified () { - webidl.brandCheck(this, FileLike) + // 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 + } - return this[kState].lastModified + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this[kHeadersList].set(name, value) } - get [Symbol.toStringTag] () { - return 'File' - } -} + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) -Object.defineProperties(File.prototype, { - [Symbol.toStringTag]: { - value: 'File', - configurable: true - }, - name: kEnumerableProperty, - lastModified: kEnumerableProperty -}) + // 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. -webidl.converters.Blob = webidl.interfaceConverter(Blob) + const list = this[kHeadersList].cookies -webidl.converters.BlobPart = function (V, opts) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) + if (list) { + return [...list] } - if ( - ArrayBuffer.isView(V) || - types.isAnyArrayBuffer(V) - ) { - return webidl.converters.BufferSource(V, opts) - } + return [] } - 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() + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] } - }, - { - key: 'type', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'endings', - converter: (value) => { - value = webidl.converters.DOMString(value) - value = value.toLowerCase() - if (value !== 'native') { - value = 'transparent' - } + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] - return value - }, - defaultValue: 'transparent' - } -]) + // 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 -/** - * @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 = [] + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const [name, value] = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. - // 2. For each 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. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: - // 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) - } + // 1. Let value be the result of getting name from list. - // 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) - ) + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) } - } 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' + this[kHeadersList][kHeadersSortedMap] = headers - // 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' + // 4. Return headers. + return headers } - 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 } - + keys () { + webidl.brandCheck(this, Headers) -/***/ }), + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') + } -/***/ 3073: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + values () { + webidl.brandCheck(this, Headers) + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') + } -const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523) -const { kState } = __nccwpck_require__(9710) -const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041) -const { webidl } = __nccwpck_require__(4222) -const { Blob, File: NativeFile } = __nccwpck_require__(181) + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile + entries () { + webidl.brandCheck(this, Headers) -// 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'] - }) + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') } - this[kState] = [] + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) } - append (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) - if (arguments.length === 3 && !isBlobLike(value)) { + if (typeof callbackFn !== 'function') { throw new TypeError( - "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." ) } - // 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 + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } - // 2. Let entry be the result of creating an entry with - // name, value, and filename if given. - const entry = makeEntry(name, value, filename) + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) - // 3. Append entry to this’s entry list. - this[kState].push(entry) + return this[kHeadersList] } +} - delete (name) { - webidl.brandCheck(this, FormData) +Headers.prototype[Symbol.iterator] = Headers.prototype.entries - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + }, + [util.inspect.custom]: { + enumerable: false + } +}) - name = webidl.converters.USVString(name) +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } - // 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) + return webidl.converters['record'](V) } - get (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} - name = webidl.converters.USVString(name) +module.exports = { + fill, + Headers, + HeadersList +} - // 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) +/***/ 2315: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) +// https://github.com/Ethan-Arrowood/undici-fetch - 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) +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = __nccwpck_require__(8676) +const { Headers } = __nccwpck_require__(6349) +const { Request, makeRequest } = __nccwpck_require__(5194) +const zlib = __nccwpck_require__(3106) +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme +} = __nccwpck_require__(5523) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) +const assert = __nccwpck_require__(2613) +const { safelyExtractBody } = __nccwpck_require__(8923) +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = __nccwpck_require__(7326) +const { kHeadersList } = __nccwpck_require__(6443) +const EE = __nccwpck_require__(4434) +const { Readable, pipeline } = __nccwpck_require__(2203) +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440) +const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322) +const { TransformStream } = __nccwpck_require__(3774) +const { getGlobalDispatcher } = __nccwpck_require__(2581) +const { webidl } = __nccwpck_require__(4222) +const { STATUS_CODES } = __nccwpck_require__(8611) +const GET_OR_HEAD = ['GET', 'HEAD'] - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream - name = webidl.converters.USVString(name) +class Fetch extends EE { + constructor (dispatcher) { + super() - // 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 + 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) } - set (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) + terminate (reason) { + if (this.state !== 'ongoing') { + return + } - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" - ) + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return } - // The set(name, value) and set(name, blobValue, filename) method steps - // are: + // 1. Set controller’s state to "aborted". + this.state = 'aborted' - // 1. Let value be value if given; otherwise blobValue. + // 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') + } - 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 + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). - // 2. Let entry be the result of creating an entry with name, value, and - // filename if given. - const entry = makeEntry(name, value, filename) + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error - // 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) - } + this.connection?.destroy(error) + this.emit('terminated', error) } +} - entries () { - webidl.brandCheck(this, FormData) +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key+value' - ) - } + // 1. Let p be a new promise. + const p = createDeferredPromise() - keys () { - webidl.brandCheck(this, FormData) + // 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 - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key' - ) + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise } - values () { - webidl.brandCheck(this, FormData) + // 3. Let request be requestObject’s request. + const request = requestObject[kState] - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'value' - ) + // 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 } - /** - * @param {(value: string, key: string, self: FormData) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, FormData) + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." - ) - } + // 7. Let responseObject be null. + let responseObject = null - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } - } -} + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null -FormData.prototype[Symbol.iterator] = FormData.prototype.entries + // 9. Let locallyAborted be false. + let locallyAborted = false -Object.defineProperties(FormData.prototype, { - [Symbol.toStringTag]: { - value: 'FormData', - configurable: true - } -}) + // 10. Let controller be null. + let controller = null -/** - * @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') + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true - // 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: + // 2. Assert: controller is non-null. + assert(controller != null) - // 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 }) + // 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) } + ) - // 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 - } + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') - value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile - ? new File([value], filename, options) - : new FileLike(value, filename, options) - } - } + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: - // 4. Return an entry whose name is name and whose value is value. - return { name, value } -} + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } -module.exports = { FormData } + // 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() + } -/***/ 5628: -/***/ ((module) => { + // 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) + } -// In case of breaking changes, increase the version -// number to avoid conflicts. -const globalOrigin = Symbol.for('undici.globalOrigin.1') + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) -function getGlobalOrigin () { - return globalThis[globalOrigin] + // 14. Return p. + return p.promise } -function setGlobalOrigin (newOrigin) { - if (newOrigin === undefined) { - Object.defineProperty(globalThis, globalOrigin, { - value: undefined, - writable: true, - enumerable: false, - configurable: false - }) - +// 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 } - const parsedURL = new URL(newOrigin) - - if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { - throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return } - Object.defineProperty(globalThis, globalOrigin, { - value: parsedURL, - writable: true, - enumerable: false, - configurable: false - }) -} - -module.exports = { - getGlobalOrigin, - setGlobalOrigin -} + // 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 -/***/ 6349: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } -// https://github.com/Ethan-Arrowood/undici-fetch + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + // 2. Set cacheState to the empty string. + cacheState = '' + } -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const { kGuard } = __nccwpck_require__(9710) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const { - makeIterator, - isValidHeaderName, - isValidHeaderValue -} = __nccwpck_require__(5523) -const util = __nccwpck_require__(9023) -const { webidl } = __nccwpck_require__(4222) -const assert = __nccwpck_require__(2613) + // 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() -const kHeadersMap = Symbol('headers map') -const kHeadersSortedMap = Symbol('headers map sorted') + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo -/** - * @param {number} code - */ -function isHTTPWhiteSpaceCharCode (code) { - return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) } -/** - * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize - * @param {string} potentialValue - */ -function headerValueNormalize (potentialValue) { - // To normalize a byte sequence potentialValue, remove - // any leading and trailing HTTP whitespace bytes from - // potentialValue. - let i = 0; let j = potentialValue.length - - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i - - return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +// 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) + } } -function fill (headers, object) { - // To fill a Headers object headers with a given object object, run these steps: - - // 1. If object is a sequence, then for each header in object: - // Note: webidl conversion to array has already been done. - if (Array.isArray(object)) { - for (let i = 0; i < object.length; ++i) { - const header = object[i] - // 1. If header does not contain exactly two items, then throw a TypeError. - if (header.length !== 2) { - throw webidl.errors.exception({ - header: 'Headers constructor', - message: `expected name/value pair to be length 2, found ${header.length}.` - }) - } +// 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') + } - // 2. Append (header’s first item, header’s second item) to headers. - appendHeader(headers, header[0], header[1]) - } - } else if (typeof object === 'object' && object !== null) { - // Note: null should throw + // 1. Reject promise with error. + p.reject(error) - // 2. Otherwise, object is a record, then for each key → value in object, - // append (key, value) to headers - const keys = Object.keys(object) - for (let i = 0; i < keys.length; ++i) { - appendHeader(headers, keys[i], object[keys[i]]) - } - } else { - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] + // 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 }) } -} -/** - * @see https://fetch.spec.whatwg.org/#concept-headers-append - */ -function appendHeader (headers, name, value) { - // 1. Normalize value. - value = headerValueNormalize(value) + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } - // 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' + // 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 }) } +} - // 3. If headers’s guard is "immutable", then throw a TypeError. - // 4. Otherwise, if headers’s guard is "request" and name is a - // forbidden header name, return. - // Note: undici does not implement forbidden header names - if (headers[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (headers[kGuard] === 'request-no-cors') { - // 5. Otherwise, if headers’s guard is "request-no-cors": - // TODO - } +// 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 - // 6. Otherwise, if headers’s guard is "response" and name is a - // forbidden response-header name, return. + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false - // 7. Append (name, value) to headers’s header list. - return headers[kHeadersList].append(name, value) + // 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 - // 8. If headers’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from headers -} + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } -class HeadersList { - /** @type {[string, string][]|null} */ - cookies = null + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO - constructor (init) { - if (init instanceof HeadersList) { - this[kHeadersMap] = new Map(init[kHeadersMap]) - this[kHeadersSortedMap] = init[kHeadersSortedMap] - this.cookies = init.cookies === null ? null : [...init.cookies] - } else { - this[kHeadersMap] = new Map(init) - this[kHeadersSortedMap] = null - } + // 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 } - // 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() + // 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) - return this[kHeadersMap].has(name) + // 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' } - clear () { - this[kHeadersMap].clear() - this[kHeadersSortedMap] = null - this.cookies = null + // 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 } - // 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) + // 10. If all of the following conditions are true: + // TODO - // 2. Append (name, value) to list. - if (exists) { - const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' - this[kHeadersMap].set(lowercaseName, { - name: exists.name, - value: `${exists.value}${delimiter}${value}` - }) + // 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 { - this[kHeadersMap].set(lowercaseName, { name, value }) - } - - if (lowercaseName === 'set-cookie') { - this.cookies ??= [] - this.cookies.push(value) + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() } } - // https://fetch.spec.whatwg.org/#concept-header-list-set - set (name, value) { - this[kHeadersSortedMap] = null - const lowercaseName = name.toLowerCase() + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' - if (lowercaseName === 'set-cookie') { - this.cookies = [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 - // 1. If list contains name, then set the value of - // the first such header to value and remove the - // others. - // 2. Otherwise, append header (name, value) to list. - this[kHeadersMap].set(lowercaseName, { name, value }) + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) } - // https://fetch.spec.whatwg.org/#concept-header-list-delete - delete (name) { - this[kHeadersSortedMap] = null - - name = name.toLowerCase() + // 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', '*') + } - if (name === 'set-cookie') { - this.cookies = null - } + // 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 + } - this[kHeadersMap].delete(name) + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO } - // https://fetch.spec.whatwg.org/#concept-header-list-get - get (name) { - const value = this[kHeadersMap].get(name.toLowerCase()) + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) - // 1. If list does not contain name, then return null. - // 2. Return the values of all headers in list whose name - // is a byte-case-insensitive match for name, - // separated from each other by 0x2C 0x20, in order. - return value === undefined ? null : value.value - } + // 17. Return fetchParam's controller + return fetchParams.controller +} - * [Symbol.iterator] () { - // use the lowercased name - for (const [name, { value }] of this[kHeadersMap]) { - yield [name, value] - } +// 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') } - get entries () { - const headers = {} + // 4. Run report Content Security Policy violations for request. + // TODO - if (this[kHeadersMap].size) { - for (const { name, value } of this[kHeadersMap].values()) { - headers[name] = value - } - } + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) - return headers + // 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? -// https://fetch.spec.whatwg.org/#headers-class -class Headers { - constructor (init = undefined) { - if (init === kConstruct) { - return - } - this[kHeadersList] = new HeadersList() + // 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 + } - // The new Headers(init) constructor steps are: + // 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) + } - // 1. Set this’s guard to "none". - this[kGuard] = 'none' + // 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 - // 2. If init is given, then fill this with init. - if (init !== undefined) { - init = webidl.converters.HeadersInit(init) - fill(this, init) - } - } + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO - // https://fetch.spec.whatwg.org/#dom-headers-append - append (name, value) { - webidl.brandCheck(this, Headers) + // 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) - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) + 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' - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } - return appendHeader(this, name, value) - } + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } - // https://fetch.spec.whatwg.org/#dom-headers-delete - delete (name) { - webidl.brandCheck(this, Headers) + // 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' + ) + } - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' - name = webidl.converters.ByteString(name) + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } - // 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' - }) - } + // 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') + } - // 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') { + // - 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 - } - // 6. If this’s header list does not contain name, then - // return. - if (!this[kHeadersList].contains(name)) { - return - } + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' - // 7. Delete name from this’s header list. - // 8. If this’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from this. - this[kHeadersList].delete(name) + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() } - // https://fetch.spec.whatwg.org/#dom-headers-get - get (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + // 12. If recursive is true, then return response. + if (recursive) { + return response + } - 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' - }) + // 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 } - // 2. Return the result of getting name from this’s header - // list. - return this[kHeadersList].get(name) + // 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) + } } - // https://fetch.spec.whatwg.org/#dom-headers-has - has (name) { - webidl.brandCheck(this, Headers) + // 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 - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + // 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) + } - name = webidl.converters.ByteString(name) + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } - // 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' - }) - } + // 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 - // 2. Return true if this’s header list contains name; - // otherwise false. - return this[kHeadersList].contains(name) + // 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() } - // https://fetch.spec.whatwg.org/#dom-headers-set - set (name, value) { - webidl.brandCheck(this, Headers) + // 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 + } - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + // 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)) - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) + // 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 + } - // 1. Normalize value. - value = headerValueNormalize(value) + // 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. 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' - }) - } + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] - // 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 + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) } - // 7. Set (name, value) in this’s header list. - // 8. If this’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from this - this[kHeadersList].set(name, value) + // 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/#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. +// 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)) + } - const list = this[kHeadersList].cookies + // 2. Let request be fetchParams’s request. + const { request } = fetchParams - if (list) { - return [...list] - } + const { protocol: scheme } = requestCurrentURL(request) - return [] - } + // 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. - // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine - get [kHeadersSortedMap] () { - if (this[kHeadersList][kHeadersSortedMap]) { - return this[kHeadersList][kHeadersSortedMap] + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL) + } - // 1. Let headers be an empty list of headers with the key being the name - // and value the value. - const headers = [] + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) - // 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 + // 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.')) + } - // 3. For each name of names: - for (let i = 0; i < names.length; ++i) { - const [name, value] = names[i] - // 1. If name is `set-cookie`, then: - if (name === 'set-cookie') { - // 1. Let values be a list of all values of headers in list whose name - // is a byte-case-insensitive match for name, in order. + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) - // 2. For each value of values: - // 1. Append (name, value) to headers. - for (let j = 0; j < cookies.length; ++j) { - headers.push([name, cookies[j]]) - } - } else { - // 2. Otherwise: + // 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')) + } - // 1. Let value be the result of getting name from list. + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) - // 2. Assert: value is non-null. - assert(value !== null) + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] - // 3. Append (name, value) to headers. - headers.push([name, value]) - } - } + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) - this[kHeadersList][kHeadersSortedMap] = headers + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' - // 4. Return headers. - return headers - } + // 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 }] + ] + }) - keys () { - webidl.brandCheck(this, Headers) + response.body = body - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key') + 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) - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key' - ) - } + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } - values () { - webidl.brandCheck(this, Headers) + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'value') + // 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 makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'value' - ) + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } } +} - entries () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key+value') - } +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key+value' - ) + // 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)) } +} - /** - * @param {(value: string, key: string, self: Headers) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers) +// 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]] - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + // 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 + }) + } - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." - ) - } + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) + // 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)) } } - [Symbol.for('nodejs.util.inspect.custom')] () { - webidl.brandCheck(this, Headers) - - return this[kHeadersList] + // 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)) } -} -Headers.prototype[Symbol.iterator] = Headers.prototype.entries + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: -Object.defineProperties(Headers.prototype, { - append: kEnumerableProperty, - delete: kEnumerableProperty, - get: kEnumerableProperty, - has: kEnumerableProperty, - set: kEnumerableProperty, - getSetCookie: kEnumerableProperty, - keys: kEnumerableProperty, - values: kEnumerableProperty, - entries: kEnumerableProperty, - forEach: kEnumerableProperty, - [Symbol.iterator]: { enumerable: false }, - [Symbol.toStringTag]: { - value: 'Headers', - configurable: true - }, - [util.inspect.custom]: { - enumerable: false - } -}) + // 1. Let transformStream be a new a TransformStream. -webidl.converters.HeadersInit = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (V[Symbol.iterator]) { - return webidl.converters['sequence>'](V) + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) } - return webidl.converters['record'](V) + // 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) } } - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) -} + // 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) -module.exports = { - fill, - Headers, - HeadersList + // 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 -/***/ 2315: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // 3. Let actualResponse be null. + let actualResponse = null -// https://github.com/Ethan-Arrowood/undici-fetch + // 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 -const { - Response, - makeNetworkError, - makeAppropriateNetworkError, - filterResponse, - makeResponse -} = __nccwpck_require__(8676) -const { Headers } = __nccwpck_require__(6349) -const { Request, makeRequest } = __nccwpck_require__(5194) -const zlib = __nccwpck_require__(3106) -const { - bytesMatch, - makePolicyContainer, - clonePolicyContainer, - requestBadPort, - TAOCheck, - appendRequestOriginHeader, - responseLocationURL, - requestCurrentURL, - setRequestReferrerPolicyOnRedirect, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - createOpaqueTimingInfo, - appendFetchMetadata, - corsCheck, - crossOriginResourcePolicyCheck, - determineRequestsReferrer, - coarsenedSharedCurrentTime, - createDeferredPromise, - isBlobLike, - sameOrigin, - isCancelled, - isAborted, - isErrorLike, - fullyReadBody, - readableStreamClose, - isomorphicEncode, - urlIsLocal, - urlIsHttpHttpsScheme, - urlHasHttpsScheme -} = __nccwpck_require__(5523) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const assert = __nccwpck_require__(2613) -const { safelyExtractBody } = __nccwpck_require__(8923) -const { - redirectStatusSet, - nullBodyStatus, - safeMethodsSet, - requestBodyHeader, - subresourceSet, - DOMException -} = __nccwpck_require__(7326) -const { kHeadersList } = __nccwpck_require__(6443) -const EE = __nccwpck_require__(4434) -const { Readable, pipeline } = __nccwpck_require__(2203) -const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440) -const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322) -const { TransformStream } = __nccwpck_require__(3774) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { webidl } = __nccwpck_require__(4222) -const { STATUS_CODES } = __nccwpck_require__(8611) -const GET_OR_HEAD = ['GET', 'HEAD'] - -/** @type {import('buffer').resolveObjectURL} */ -let resolveObjectURL -let ReadableStream = globalThis.ReadableStream + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } -class Fetch extends EE { - constructor (dispatcher) { - super() + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) - 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) - } + // 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') + } - terminate (reason) { - if (this.state !== 'ongoing') { - return + // 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 } + } - this.state = 'terminated' - this.connection?.destroy(reason) - this.emit('terminated', reason) + // 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') } - // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort (error) { - if (this.state !== 'ongoing') { - return + // 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() } - // 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') + // 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) } + } - // 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 + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo - this.connection?.destroy(error) - this.emit('terminated', error) - } + // 10. Return response. + return response } -// https://fetch.spec.whatwg.org/#fetch-method -function fetch (input, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request - // 1. Let p be a new promise. - const p = createDeferredPromise() + // 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 - // 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 + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL try { - requestObject = new Request(input, init) - } catch (e) { - p.reject(e) - return p.promise - } + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) - // 3. Let request be requestObject’s request. - const request = requestObject[kState] + // 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)) + } - // 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) + // 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')) + } - // 2. Return p. - return p.promise + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) } - // 5. Let globalObject be request’s client’s global object. - const globalObject = request.client.globalObject + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 - // 6. If globalObject is a ServiceWorkerGlobalScope object, then set - // request’s service-workers mode to "none". - if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { - request.serviceWorkers = 'none' + // 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"')) } - // 7. Let responseObject be null. - let responseObject = null + // 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"' + )) + } - // 8. Let relevantRealm be this’s relevant Realm. - const relevantRealm = null + // 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()) + } - // 9. Let locallyAborted be false. - let locallyAborted = false + // 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 - // 10. Let controller be null. - let controller = 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) + } + } - // 11. Add the following abort steps to requestObject’s signal: - addAbortListener( - requestObject.signal, - () => { - // 1. Set locallyAborted to true. - locallyAborted = true + // 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') - // 2. Assert: controller is non-null. - assert(controller != null) + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) - // 3. Abort controller with requestObject’s signal’s abort reason. - controller.abort(requestObject.signal.reason) + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') + } - // 4. Abort the fetch() call with p, request, responseObject, - // and requestObject’s signal’s abort reason. - abortFetch(p, request, responseObject, requestObject.signal.reason) - } - ) + // 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] + } - // 12. Let handleFetchDone given response response be to finalize and - // report timing with response, globalObject, and "fetch". - const handleFetchDone = (response) => - finalizeAndReportTiming(response, 'fetch') + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo - // 13. Set controller to the result of calling fetch given request, - // with processResponseEndOfBody set to handleFetchDone, and processResponse - // given response being these substeps: + // 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) - const processResponse = (response) => { - // 1. If locallyAborted is true, terminate these substeps. - if (locallyAborted) { - return Promise.resolve() - } + // 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 + } - // 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. + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) - // 2. Abort the fetch() call with p, request, responseObject, and - // deserializedError. + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) - abortFetch(p, request, responseObject, controller.serializedAbortReason) - return Promise.resolve() - } + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} - // 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() - } +// 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 - // 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 + // 2. Let httpFetchParams be null. + let httpFetchParams = null - // 5. Resolve p with responseObject. - p.resolve(responseObject) - } + // 3. Let httpRequest be null. + let httpRequest = null - controller = fetching({ - request, - processResponseEndOfBody: handleFetchDone, - processResponse, - dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici - }) + // 4. Let response be null. + let response = null - // 14. Return p. - return p.promise -} + // 5. Let storedResponse be null. + // TODO: cache -// 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 - } + // 6. Let httpCache be null. + const httpCache = null - // 2. If response’s URL list is null or empty, then return. - if (!response.urlList?.length) { - return - } + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false - // 3. Let originalURL be response’s URL list[0]. - const originalURL = response.urlList[0] + // 8. Run these steps, but abort when the ongoing fetch is terminated: - // 4. Let timingInfo be response’s timing info. - let timingInfo = response.timingInfo + // 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: - // 5. Let cacheState be response’s cache state. - let cacheState = response.cacheState + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) - // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. - if (!urlIsHttpHttpsScheme(originalURL)) { - return - } + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } - // 7. If timingInfo is null, then return. - if (timingInfo === null) { - return + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest } - // 8. If response’s timing allow passed flag is not set, then: - if (!response.timingAllowPassed) { - // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. - timingInfo = createOpaqueTimingInfo({ - startTime: timingInfo.startTime - }) - - // 2. Set cacheState to the empty string. - cacheState = '' - } + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') - // 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() + // 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 - // 10. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null - // 11. Mark resource timing for timingInfo, originalURL, initiatorType, - // global, and cacheState. - markResourceTiming( - timingInfo, - originalURL, - initiatorType, - globalThis, - cacheState - ) -} + // 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' + } -// 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) + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) } -} -// 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') + // 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) } - // 1. Reject promise with error. - p.reject(error) + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. - // 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 - }) + // 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. } - // 3. If responseObject is null, then return. - if (responseObject == null) { - return + // 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)) } - // 4. Let response be responseObject’s response. - const response = responseObject[kState] + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) - // 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 - }) + // 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') } -} -// 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 + // 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' + } - // 2. Let crossOriginIsolatedCapability be false. - let crossOriginIsolatedCapability = false + // 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') + } - // 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 + // 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. Set crossOriginIsolatedCapability to request’s client’s cross-origin - // isolated capability. - crossOriginIsolatedCapability = - request.client.crossOriginIsolatedCapability + // 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') + } } - // 4. If useParallelQueue is true, then set taskDestination to the result of - // starting a new parallel queue. - // TODO + // 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') + } - // 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 - }) + // 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') + } + } - // 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 + 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 } - // 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) + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication - // 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' + // 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' } - // 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 + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache } - // 10. If all of the following conditions are true: + // 9. If aborted, then return the appropriate network error for fetchParams. // 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() + // 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') } - } - // 12. If request’s header list does not contain `Accept`, then: - if (!request.headersList.contains('accept')) { - // 1. Let value be `*/*`. - const value = '*/*' + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) - // 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. 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 + } - // 3. Append `Accept`/value to request’s header list. - request.headersList.append('accept', value) + // 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 + } } - // 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', '*') + // 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 } - // 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) { + // 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') } - // 15. If request is a subresource request, then: - if (subresourceSet.has(request.destination)) { - // TODO + // 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 + ) } - // 16. Run main fetch given fetchParams. - mainFetch(fetchParams) - .catch(err => { - fetchParams.controller.terminate(err) - }) + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } - // 17. Return fetchParam's controller - return fetchParams.controller + // 18. Return response. + return response } -// https://fetch.spec.whatwg.org/#concept-main-fetch -async function mainFetch (fetchParams, recursive = false) { +// 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. 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') + // 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' } - // 4. Run report Content Security Policy violations for request. + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. // TODO - // 5. Upgrade request to a potentially trustworthy URL, if appropriate. - tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars - // 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') + // 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 } - // 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 - } + // 9. Run these steps, but abort when the ongoing fetch is terminated: - // 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) - } + // 1. If connection is failure, then return a network error. - // 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 + // 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. - // 10. If recursive is false, then run the remaining steps in parallel. - // TODO + // 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. - // 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) + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. - 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' + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: - // 2. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] - // request’s mode is "same-origin" - if (request.mode === 'same-origin') { - // 1. Return a network error. - return makeNetworkError('request mode cannot be "same-origin"') - } + // - 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. - // 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' - ) - } + // - 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). - // 2. Set request’s response tainting to "opaque". - request.responseTainting = 'opaque' + // - Wait until all the headers are transmitted. - // 3. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } + // - 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. - // 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') - } + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. - // - 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 + // - If the HTTP request results in a TLS client certificate dialog, then: - // Otherwise - // 1. Set request’s response tainting to "cors". - request.responseTainting = 'cors' + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. - // 2. Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) - })() - } + // 2. Otherwise, return a network error. - // 12. If recursive is true, then return response. - if (recursive) { - return response - } + // 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: - // 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 - } + // 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 + } - // 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) + // 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) } - } - // 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 + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } - // 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) - } + // 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() + } + } - // 16. If request’s timing allow failed flag is unset, then set - // internalResponse’s timing allow passed flag. - if (!request.timingAllowFailed) { - response.timingAllowPassed = true - } + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } - // 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 + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } - // 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() + // 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) + } + })() } - // 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 - } + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) - // 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)) + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() - // 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 + 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() - // 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) + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) } - // 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) + return makeNetworkError(err) } -} -// 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)) + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() } - // 2. Let request be fetchParams’s request. - const { request } = fetchParams - - const { protocol: scheme } = requestCurrentURL(request) + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } - // 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. + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO - // Otherwise, return a network error. - return Promise.resolve(makeNetworkError('about scheme is not supported')) - } - case 'blob:': { - if (!resolveObjectURL) { - resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL) - } + // 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 - // 1. Let blobURLEntry be request’s current URL’s blob URL entry. - const blobURLEntry = requestCurrentURL(request) + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } - // 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 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 } + } + ) - const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + // 17. Run these steps, but abort when the ongoing fetch is terminated: - // 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')) - } + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } - // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. - const bodyWithType = safelyExtractBody(blobURLEntryObject) + // 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 - // 4. Let body be bodyWithType’s body. - const body = bodyWithType[0] + // 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 - // 5. Let length be body’s length, serialized and isomorphic encoded. - const length = isomorphicEncode(`${body.length}`) + // 18. If aborted, then: + // TODO - // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. - const type = bodyWithType[1] ?? '' + // 19. Run these steps in parallel: - // 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 }] - ] - }) + // 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... - response.body = body + // 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() - 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) + if (isAborted(fetchParams)) { + break + } - // 2. If dataURLStruct is failure, then return a - // network error. - if (dataURLStruct === 'failure') { - return Promise.resolve(makeNetworkError('failed to fetch the data URL')) - } + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err - // 3. Let mimeType be dataURLStruct’s MIME type, serialized. - const mimeType = serializeAMimeType(dataURLStruct.mimeType) + // 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 + } + } - // 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. + 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) - return httpFetch(fetchParams) - .catch((err) => makeNetworkError(err)) - } - default: { - return Promise.resolve(makeNetworkError('unknown scheme')) - } - } -} + finalizeResponse(fetchParams, response) -// https://fetch.spec.whatwg.org/#finalize-response -function finalizeResponse (fetchParams, response) { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true + return + } - // 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)) - } -} + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 -// 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]] + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } - // 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 - }) - } + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) - // 2. Let processResponseEndOfBody be the following steps: - const processResponseEndOfBody = () => { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } - // 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)) + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } } } - // 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) - } + // 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 - // 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 + // 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 + ) } - }, { - size () { - return 1 + } 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. Set response’s body to the result of piping response’s body through transformStream. - response.body = { stream: response.body.stream.pipeThrough(transformStream) } + // 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() } - // 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) + // 20. Return response. + return response - // 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() - } -} + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher -// https://fetch.spec.whatwg.org/#http-fetch -async function httpFetch (fetchParams) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, - // 2. Let response be null. - let response = null + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller - // 3. Let actualResponse be null. - let actualResponse = null + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, - // 4. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } - // 5. If request’s service-workers mode is "all", then: - if (request.serviceWorkers === 'all') { - // TODO - } + let codings = [] + let location = '' - // 6. If response is null, then: - if (response === null) { - // 1. If makeCORSPreflight is true and one of these conditions is true: - // TODO + const headers = new Headers() - // 2. If request’s redirect mode is "follow", then set request’s - // service-workers mode to "none". - if (request.redirect === 'follow') { - request.serviceWorkers = 'none' - } + // 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 + } - // 3. Set response and actualResponse to the result of running - // HTTP-network-or-cache fetch given fetchParams. - actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + headers[kHeadersList].append(key, val) + } + } else { + const keys = Object.keys(headersList) + for (const key of keys) { + const val = headersList[key] + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() + } else if (key.toLowerCase() === 'location') { + location = val + } - // 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') - } + headers[kHeadersList].append(key, val) + } + } - // 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 - } - } + this.body = new Readable({ read: resume }) - // 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') - } + const decoders = [] - // 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() - } + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) - // 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) - } - } + // 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 + } + } + } - // 9. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) - // 10. Return response. - return response -} + return true + }, -// https://fetch.spec.whatwg.org/#http-redirect-fetch -function httpRedirectFetch (fetchParams, response) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request + onData (chunk) { + if (fetchParams.controller.dump) { + return + } - // 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 + // 1. If one or more bytes have been transmitted from response’s + // message body, then: - // 3. Let locationURL be actualResponse’s location URL given request’s current - // URL’s fragment. - let locationURL + // 1. Let bytes be the transmitted bytes. + const bytes = chunk - try { - locationURL = responseLocationURL( - actualResponse, - requestCurrentURL(request).hash - ) + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. - // 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)) - } + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength - // 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')) - } + // 4. See pullAlgorithm... - // 7. If request’s redirect count is 20, then return a network error. - if (request.redirectCount === 20) { - return Promise.resolve(makeNetworkError('redirect count exceeded')) - } + return this.body.push(bytes) + }, - // 8. Increase request’s redirect count by 1. - request.redirectCount += 1 + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } - // 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"')) - } + fetchParams.controller.ended = true - // 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"' - )) - } + this.body.push(null) + }, - // 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()) - } + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } - // 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 + this.body?.destroy(error) - // 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) - } - } + fetchParams.controller.terminate(error) - // 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') + reject(error) + }, - // https://fetch.spec.whatwg.org/#authentication-entries - request.headersList.delete('proxy-authorization', true) + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } - // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. - request.headersList.delete('cookie') - request.headersList.delete('host') - } + const headers = new Headers() - // 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] - } + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') - // 15. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + headers[kHeadersList].append(key, val) + } - // 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) + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) - // 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 + return true + } + } + )) } +} - // 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) +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming } -// 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 +/***/ 5194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 4. Let response be null. - let response = null +/* globals AbortController */ - // 5. Let storedResponse be null. - // TODO: cache - // 6. Let httpCache be null. - const httpCache = null - // 7. Let the revalidatingFlag be unset. - const revalidatingFlag = false +const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923) +const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349) +const { FinalizationRegistry } = __nccwpck_require__(3194)() +const util = __nccwpck_require__(3440) +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = __nccwpck_require__(5523) +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = __nccwpck_require__(7326) +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710) +const { webidl } = __nccwpck_require__(4222) +const { getGlobalOrigin } = __nccwpck_require__(5628) +const { URLSerializer } = __nccwpck_require__(4322) +const { kHeadersList, kConstruct } = __nccwpck_require__(6443) +const assert = __nccwpck_require__(2613) +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434) - // 8. Run these steps, but abort when the ongoing fetch is terminated: +let TransformStream = globalThis.TransformStream - // 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: +const kAbortController = Symbol('abortController') - // 1. Set httpRequest to a clone of request. - httpRequest = makeRequest(request) +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) - // 2. Set httpFetchParams to a copy of fetchParams. - httpFetchParams = { ...fetchParams } +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { + return + } - // 3. Set httpFetchParams’s request to httpRequest. - httpFetchParams.request = httpRequest - } + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) - // 3. Let includeCredentials be true if one of - const includeCredentials = - request.credentials === 'include' || - (request.credentials === 'same-origin' && - request.responseTainting === 'basic') + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) - // 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 + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + } - // 5. Let contentLengthHeaderValue be null. - let contentLengthHeaderValue = null + // 1. Let request be null. + let request = 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' - } + // 2. Let fallbackMode be null. + let fallbackMode = null - // 7. If contentLength is non-null, then set contentLengthHeaderValue to - // contentLength, serialized and isomorphic encoded. - if (contentLength != null) { - contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) - } + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl - // 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) - } + // 4. Let signal be null. + let signal = null - // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, - // contentLengthHeaderValue) to httpRequest’s header list. + // 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 }) + } - // 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. - } + // 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 + ) + } - // 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)) - } + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) - // 12. Append a request `Origin` header for httpRequest. - appendRequestOriginHeader(httpRequest) + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: - // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] - appendFetchMetadata(httpRequest) + // 7. Assert: input is a Request object. + assert(input instanceof Request) - // 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') - } + // 8. Set request to input’s request. + request = input[kState] - // 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' - } + // 9. Set signal to input’s signal. + signal = input[kSignal] + } - // 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') - } + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin - // 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') - } + // 8. Let window be "client". + let window = 'client' - // 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') + // 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 } - } - // 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') - } + // 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`) + } - // 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') + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' } - } - httpRequest.headersList.delete('host') + // 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] + }) - // 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 - } + const initHasKey = Object.keys(init).length !== 0 - // 21. If there’s a proxy-authentication entry, use it as appropriate. - // TODO: proxy-authentication + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } - // 22. Set httpCache to the result of determining the HTTP cache - // partition, given httpRequest. - // TODO: cache + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false - // 23. If httpCache is null, then set httpRequest’s cache mode to - // "no-store". - if (httpCache == null) { - httpRequest.cache = 'no-store' - } + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false - // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", - // then: - if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { - // TODO: cache - } + // 4. Set request’s origin to "client". + request.origin = 'client' - // 9. If aborted, then return the appropriate network error for fetchParams. - // TODO + // 5. Set request’s referrer to "client" + request.referrer = 'client' - // 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') + // 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] } - // 2. Let forwardResponse be the result of running HTTP-network fetch - // given httpFetchParams, includeCredentials, and isNewConnectionFetch. - const forwardResponse = await httpNetworkFetch( - httpFetchParams, - includeCredentials, - isNewConnectionFetch - ) + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer - // 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 + // 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 + } + } } - // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, - // then: - if (revalidatingFlag && forwardResponse.status === 304) { - // TODO: cache + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy } - // 5. If response is null, then: - if (response == null) { - // 1. Set response to forwardResponse. - response = forwardResponse + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } - // 2. Store httpRequest and forwardResponse in httpCache, as per the - // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] - // TODO: cache + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) } - } - // 11. Set response’s URL list to a clone of httpRequest’s URL list. - response.urlList = [...httpRequest.urlList] + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } - // 12. If httpRequest’s header list contains `Range`, then set response’s - // range-requested flag. - if (httpRequest.headersList.contains('range')) { - response.rangeRequested = true - } + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } - // 13. Set response’s request-includes-credentials to includeCredentials. - response.requestIncludesCredentials = includeCredentials + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } - // 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 + // 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" + ) + } - // 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() + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect } - // 2. ??? + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } - // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) } - // 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? + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method - // 5. Set response to the result of running HTTP-network-or-cache fetch given - // fetchParams. - // TODO - return makeNetworkError('proxy authentication required') - } + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } - // 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: + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } - // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) + + // 4. Set request’s method to method. + request.method = method } - // 2. Set response to the result of running HTTP-network-or-cache - // fetch given fetchParams, isAuthenticationFetch, and true. + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } - // 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() + // 27. Set this’s request to request. + this[kState] = request - response = await httpNetworkOrCacheFetch( - fetchParams, - isAuthenticationFetch, - true - ) - } + // 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] - // 17. If isAuthenticationFetch is true, then create an authentication entry - if (isAuthenticationFetch) { - // TODO - } + // 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." + ) + } - // 18. Return response. - return response -} + 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 -// https://fetch.spec.whatwg.org/#http-network-fetch -async function httpNetworkFetch ( - fetchParams, - includeCredentials = false, - forceNewConnection = false -) { - assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) + } + } - 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')) + // 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 }) } } - } - - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - // 2. Let response be null. - let response = null + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] - // 3. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo + // 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.` + ) + } - // 4. Let httpCache be the result of determining the HTTP cache partition, - // given request. - // TODO: cache - const httpCache = null + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } - // 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. + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = this[kHeaders][kHeadersList] + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) - // 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. Empty this’s headers’s header list. + headersList.clear() - // 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. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const [key, val] of headers) { + headersList.append(key, val) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } - // 4. Set timingInfo’s final network-request start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated - // capability. + // 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 - // 5. Set response to the result of making an HTTP request over connection - // using request with the following caveats: + // 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.') + } - // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] - // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + // 35. Let initBody be null. + let initBody = null - // - 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. + // 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 - // - 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). + // 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) + } + } - // - Wait until all the headers are transmitted. + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody - // - 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. + // 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.') + } - // - If request’s header list contains `Transfer-Encoding`/`chunked` and - // response is transferred via HTTP/1.0 or older, then return a network - // error. + // 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"' + ) + } - // - If the HTTP request results in a TLS client certificate dialog, then: + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } - // 1. If request’s window is an environment settings object, make the - // dialog available in request’s window. + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody - // 2. Otherwise, return a network error. + // 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.' + ) + } - // 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: + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = (__nccwpck_require__(3774).TransformStream) + } - // 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 + // 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 } + } - // 2. Run this step in parallel: transmit bytes. - yield bytes + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } - // 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) - } + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) - // 2. Let processEndOfBody be these steps: - const processEndOfBody = () => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } + // The method getter steps are to return this’s request’s method. + return this[kState].method + } - // 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() - } - } + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) - // 3. Let processBodyError given e be these steps: - const processBodyError = (e) => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } - // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. - if (e.name === 'AbortError') { - fetchParams.controller.abort() - } else { - fetchParams.controller.terminate(e) - } - } + // 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) - // 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) - } - })() + // The headers getter steps are to return this’s headers. + return this[kHeaders] } - try { - // socket is only provided for websockets - const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) - if (socket) { - response = makeResponse({ status, statusText, headersList, socket }) - } else { - const iterator = body[Symbol.asyncIterator]() - fetchParams.controller.next = () => iterator.next() + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } - response = makeResponse({ status, statusText, headersList }) + // 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 '' } - } 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) + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' } - return makeNetworkError(err) + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() } - // 11. Let pullAlgorithm be an action that resumes the ongoing fetch - // if it is suspended. - const pullAlgorithm = () => { - fetchParams.controller.resume() - } + // 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) - // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s - // controller with reason, given reason. - const cancelAlgorithm = (reason) => { - fetchParams.controller.abort(reason) + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy } - // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by - // the user agent. - // TODO + // 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) - // 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 + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } - // 15. Let stream be a new ReadableStream. - // 16. Set up stream with pullAlgorithm set to pullAlgorithm, - // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to - // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) + // 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 } - 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 - } - } - ) + // 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) - // 17. Run these steps, but abort when the ongoing fetch is terminated: + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } - // 1. Set response’s body to a new body whose stream is stream. - response.body = { stream } + // 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) - // 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 + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } - // 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 + // 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) - // 18. If aborted, then: - // TODO + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } - // 19. Run these steps in parallel: + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) - // 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... + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } - // 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() + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) - if (isAborted(fetchParams)) { - break - } + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } - bytes = done ? undefined : value - } catch (err) { - if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { - // zlib doesn't like empty streams. - bytes = undefined - } else { - bytes = err + // 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) - // 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 - } - } + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } - 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) + // 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) - finalizeResponse(fetchParams, response) + // The signal getter steps are to return this’s signal. + return this[kSignal] + } - return - } + get body () { + webidl.brandCheck(this, Request) - // 5. Increase timingInfo’s decoded body size by bytes’s length. - timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + return this[kState].body ? this[kState].body.stream : null + } - // 6. If bytes is failure, then terminate fetchParams’s controller. - if (isFailure) { - fetchParams.controller.terminate(bytes) - return - } + get bodyUsed () { + webidl.brandCheck(this, Request) - // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes - // into stream. - fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } - // 8. If stream is errored, then terminate the ongoing fetch. - if (isErrored(stream)) { - fetchParams.controller.terminate() - return - } + get duplex () { + webidl.brandCheck(this, Request) - // 9. If stream doesn’t need more data ask the user agent to suspend - // the ongoing fetch. - if (!fetchParams.controller.controller.desiredSize) { - return - } - } + return 'half' } - // 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 + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) - // 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 - })) - } + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') } - // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. - // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. - fetchParams.controller.connection.destroy() - } - - // 20. Return response. - return response - - async function dispatch ({ body }) { - const url = requestCurrentURL(request) - /** @type {import('../..').Agent} */ - const agent = fetchParams.controller.dispatcher - - return new Promise((resolve, reject) => agent.dispatch( - { - path: url.pathname + url.search, - origin: url.origin, - method: request.method, - body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, - headers: request.headersList.entries, - maxRedirections: 0, - upgrade: request.mode === 'websocket' ? 'websocket' : undefined - }, - { - body: null, - abort: null, - - onConnect (abort) { - // TODO (fix): Do we need connection here? - const { connection } = fetchParams.controller - - if (connection.destroyed) { - abort(new DOMException('The operation was aborted.', 'AbortError')) - } else { - fetchParams.controller.on('terminated', abort) - this.abort = connection.abort = abort - } - }, - - onHeaders (status, headersList, resume, statusText) { - if (status < 200) { - return - } - - let codings = [] - let location = '' - - const headers = new Headers() - - // For H2, the headers are a plain JS object - // We distinguish between them and iterate accordingly - if (Array.isArray(headersList)) { - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') - if (key.toLowerCase() === 'content-encoding') { - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 - // "All content-coding values are case-insensitive..." - codings = val.toLowerCase().split(',').map((x) => x.trim()) - } else if (key.toLowerCase() === 'location') { - location = val - } - - headers[kHeadersList].append(key, val) - } - } else { - const keys = Object.keys(headersList) - for (const key of keys) { - const val = headersList[key] - if (key.toLowerCase() === 'content-encoding') { - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 - // "All content-coding values are case-insensitive..." - codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() - } else if (key.toLowerCase() === 'location') { - location = val - } - - headers[kHeadersList].append(key, val) - } - } - - this.body = new Readable({ read: resume }) - - const decoders = [] - - const willFollow = request.redirect === 'follow' && - location && - redirectStatusSet.has(status) - - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { - for (const coding of codings) { - // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 - if (coding === 'x-gzip' || coding === 'gzip') { - decoders.push(zlib.createGunzip({ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: zlib.constants.Z_SYNC_FLUSH - })) - } else if (coding === 'deflate') { - decoders.push(zlib.createInflate()) - } else if (coding === 'br') { - decoders.push(zlib.createBrotliDecompress()) - } else { - decoders.length = 0 - break - } - } - } - - resolve({ - status, - statusText, - headersList: headers[kHeadersList], - body: decoders.length - ? pipeline(this.body, ...decoders, () => { }) - : this.body.on('error', () => {}) - }) - - return true - }, - - onData (chunk) { - if (fetchParams.controller.dump) { - return - } - - // 1. If one or more bytes have been transmitted from response’s - // message body, then: - - // 1. Let bytes be the transmitted bytes. - const bytes = chunk - - // 2. Let codings be the result of extracting header list values - // given `Content-Encoding` and response’s header list. - // See pullAlgorithm. + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) - // 3. Increase timingInfo’s encoded body size by bytes’s length. - timingInfo.encodedBodySize += bytes.byteLength + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kConstruct) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers(kConstruct) + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] - // 4. See pullAlgorithm... + // 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 - return this.body.push(bytes) - }, + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} - onComplete () { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } +mixinBody(Request) - fetchParams.controller.ended = true +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 +} - this.body.push(null) - }, +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: - onError (error) { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) - this.body?.destroy(error) + // 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) + } - fetchParams.controller.terminate(error) + // 3. Return newRequest. + return newRequest +} - reject(error) - }, +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 + } +}) - onUpgrade (status, headersList, socket) { - if (status !== 101) { - return - } +webidl.converters.Request = webidl.interfaceConverter( + Request +) - const headers = new Headers() +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') + if (V instanceof Request) { + return webidl.converters.Request(V) + } - headers[kHeadersList].append(key, val) - } + return webidl.converters.USVString(V) +} - resolve({ - status, - statusText: STATUS_CODES[status], - headersList: headers[kHeadersList], - socket - }) +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) - return true - } - } - )) +// 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 = { - fetch, - Fetch, - fetching, - finalizeAndReportTiming -} +module.exports = { Request, makeRequest } /***/ }), -/***/ 5194: +/***/ 8676: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* globals AbortController */ - -const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923) -const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349) -const { FinalizationRegistry } = __nccwpck_require__(3194)() +const { Headers, HeadersList, fill } = __nccwpck_require__(6349) +const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923) const util = __nccwpck_require__(3440) +const { kEnumerableProperty } = util const { - isValidHTTPToken, - sameOrigin, - normalizeMethod, - makePolicyContainer, - normalizeMethodRecord + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode } = __nccwpck_require__(5523) const { - forbiddenMethodsSet, - corsSafeListedMethodsSet, - referrerPolicy, - requestRedirect, - requestMode, - requestCredentials, - requestCache, - requestDuplex + redirectStatusSet, + nullBodyStatus, + DOMException } = __nccwpck_require__(7326) -const { kEnumerableProperty } = util -const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) const { webidl } = __nccwpck_require__(4222) +const { FormData } = __nccwpck_require__(3073) const { getGlobalOrigin } = __nccwpck_require__(5628) const { URLSerializer } = __nccwpck_require__(4322) const { kHeadersList, kConstruct } = __nccwpck_require__(6443) const assert = __nccwpck_require__(2613) -const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434) +const { types } = __nccwpck_require__(9023) -let TransformStream = globalThis.TransformStream +const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream) +const textEncoder = new TextEncoder('utf-8') -const kAbortController = Symbol('abortController') +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } -const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { - signal.removeEventListener('abort', abort) -}) + // 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/#request-class -class Request { - // https://fetch.spec.whatwg.org/#dom-request - constructor (input, init = {}) { - if (input === kConstruct) { - return + // 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) } - webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) - input = webidl.converters.RequestInfo(input) - init = webidl.converters.RequestInit(init) + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) - // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object - this[kRealm] = { - settingsObject: { - baseUrl: getGlobalOrigin(), - get origin () { - return this.baseUrl?.origin - }, - policyContainer: makePolicyContainer() - } - } + // 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 - // 1. Let request be null. - let request = null + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) - // 2. Let fallbackMode be null. - let fallbackMode = null + // 5. Return responseObject. + return responseObject + } - // 3. Let baseURL be this’s relevant settings object’s API base URL. - const baseUrl = this[kRealm].settingsObject.baseUrl + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } - // 4. Let signal be null. - let signal = null + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) - // 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] + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) - // 9. Set signal to input’s signal. - signal = input[kSignal] + // 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 + }) } - // 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 + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) } - // 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`) - } + // 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 - // 11. If init["window"] exists, then set window to "no-window". - if ('window' in init) { - window = 'no-window' - } + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status - // 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] - }) + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) - const initHasKey = Object.keys(init).length !== 0 + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) - // 13. If init is not empty, then: - if (initHasKey) { - // 1. If request’s mode is "navigate", then set it to "same-origin". - if (request.mode === 'navigate') { - request.mode = 'same-origin' - } + // 8. Return responseObject. + return responseObject + } - // 2. Unset request’s reload-navigation flag. - request.reloadNavigation = false + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } - // 3. Unset request’s history-navigation flag. - request.historyNavigation = false + init = webidl.converters.ResponseInit(init) - // 4. Set request’s origin to "client". - request.origin = 'client' + // TODO + this[kRealm] = { settingsObject: {} } - // 5. Set request’s referrer to "client" - request.referrer = 'client' + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) - // 6. Set request’s referrer policy to the empty string. - request.referrerPolicy = '' + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] - // 7. Set request’s URL to request’s current URL. - request.url = request.urlList[request.urlList.length - 1] + // 3. Let bodyWithType be null. + let bodyWithType = null - // 8. Set request’s URL list to « request’s URL ». - request.urlList = [request.url] + // 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 } } - // 14. If init["referrer"] exists, then: - if (init.referrer !== undefined) { - // 1. Let referrer be init["referrer"]. - const referrer = init.referrer + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } - // 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 }) - } + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) - // 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 - } - } - } + // The type getter steps are to return this’s response’s type. + return this[kState].type + } - // 15. If init["referrerPolicy"] exists, then set request’s referrer policy - // to it. - if (init.referrerPolicy !== undefined) { - request.referrerPolicy = init.referrerPolicy - } + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) - // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. - let mode - if (init.mode !== undefined) { - mode = init.mode - } else { - mode = fallbackMode - } + const urlList = this[kState].urlList - // 17. If mode is "navigate", then throw a TypeError. - if (mode === 'navigate') { - throw webidl.errors.exception({ - header: 'Request constructor', - message: 'invalid request mode navigate.' - }) - } + // 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 - // 18. If mode is non-null, set request’s mode to mode. - if (mode != null) { - request.mode = mode + if (url === null) { + return '' } - // 19. If init["credentials"] exists, then set request’s credentials mode - // to it. - if (init.credentials !== undefined) { - request.credentials = init.credentials - } + return URLSerializer(url, true) + } - // 18. If init["cache"] exists, then set request’s cache mode to it. - if (init.cache !== undefined) { - request.cache = init.cache - } + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) - // 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" - ) - } + // 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 + } - // 22. If init["redirect"] exists, then set request’s redirect mode to it. - if (init.redirect !== undefined) { - request.redirect = init.redirect - } + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) - // 23. If init["integrity"] exists, then set request’s integrity metadata to it. - if (init.integrity != null) { - request.integrity = String(init.integrity) - } + // The status getter steps are to return this’s response’s status. + return this[kState].status + } - // 24. If init["keepalive"] exists, then set request’s keepalive to it. - if (init.keepalive !== undefined) { - request.keepalive = Boolean(init.keepalive) - } + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) - // 25. If init["method"] exists, then: - if (init.method !== undefined) { - // 1. Let method be init["method"]. - let method = init.method + // 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 + } - // 2. If method is not a method or method is a forbidden method, then - // throw a TypeError. - if (!isValidHTTPToken(method)) { - throw new TypeError(`'${method}' is not a valid HTTP method.`) - } + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) - if (forbiddenMethodsSet.has(method.toUpperCase())) { - throw new TypeError(`'${method}' HTTP method is unsupported.`) - } + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } - // 3. Normalize method. - method = normalizeMethodRecord[method] ?? normalizeMethod(method) + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) - // 4. Set request’s method to method. - request.method = method - } + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } - // 26. If init["signal"] exists, then set signal to it. - if (init.signal !== undefined) { - signal = init.signal - } + get body () { + webidl.brandCheck(this, Response) - // 27. Set this’s request to request. - this[kState] = request + return this[kState].body ? this[kState].body.stream : null + } - // 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] + get bodyUsed () { + webidl.brandCheck(this, Response) - // 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." - ) - } + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } - 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 + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) - const acRef = new WeakRef(ac) - const abort = function () { - const ac = acRef.deref() - if (ac !== undefined) { - ac.abort(this.reason) - } - } + // 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.' + }) + } - // 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 {} + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) - util.addAbortListener(signal, abort) - requestFinalizer.register(ac, { signal, abort }) - } - } + // 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] - // 30. Set this’s headers to a new Headers object with this’s relevant - // Realm, whose header list is request’s header list and guard is - // "request". - this[kHeaders] = new Headers(kConstruct) - this[kHeaders][kHeadersList] = request.headersList - this[kHeaders][kGuard] = 'request' - this[kHeaders][kRealm] = this[kRealm] + return clonedResponseObject + } +} - // 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.` - ) - } +mixinBody(Response) - // 2. Set this’s headers’s guard to "request-no-cors". - this[kHeaders][kGuard] = 'request-no-cors' - } +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 + } +}) - // 32. If init is not empty, then: - if (initHasKey) { - /** @type {HeadersList} */ - const headersList = this[kHeaders][kHeadersList] - // 1. Let headers be a copy of this’s headers and its associated header - // list. - // 2. If init["headers"] exists, then set headers to init["headers"]. - const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) - // 3. Empty this’s headers’s header list. - headersList.clear() +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: - // 4. If headers is a Headers object, then for each header in its header - // list, append header’s name/header’s value to this’s headers. - if (headers instanceof HeadersList) { - for (const [key, val] of headers) { - headersList.append(key, val) - } - // Note: Copy the `set-cookie` meta-data. - headersList.cookies = headers.cookies - } else { - // 5. Otherwise, fill this’s headers with headers. - fillHeaders(this[kHeaders], headers) - } - } + // 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 + ) + } - // 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 + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, 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.') - } + // 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) + } - // 35. Let initBody be null. - let initBody = null + // 4. Return newResponse. + return newResponse +} - // 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 +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] : [] + } +} - // 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.') - } +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' + }) +} - // 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"' - ) - } +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } - // 3. Set this’s request’s use-CORS-preflight flag. - request.useCORSPreflightFlag = true + 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 } + }) +} - // 39. Let finalBody be inputOrInitBody. - let finalBody = inputOrInitBody +// 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. - // 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.' - ) - } + // 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. - // 2. Set finalBody to the result of creating a proxy for inputBody. - if (!TransformStream) { - TransformStream = (__nccwpck_require__(3774).TransformStream) - } + // 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. - // 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 - } - } + 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. - // 41. Set this’s request’s body to finalBody. - this[kState].body = finalBody + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) } +} - // Returns request’s HTTP method, which is "GET" by default. - get method () { - webidl.brandCheck(this, Request) +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) - // The method getter steps are to return this’s request’s method. - return this[kState].method + // 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.') } - // Returns the URL of request as a string. - get url () { - webidl.brandCheck(this, Request) + // 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') + } + } - // The url getter steps are to return this’s request’s URL, serialized. - return URLSerializer(this[kState].url) + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status } - // 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) + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } - // The headers getter steps are to return this’s headers. - return this[kHeaders] + // 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) } - // Returns the kind of resource requested by request, e.g., "document" - // or "script". - get destination () { - webidl.brandCheck(this, Request) + // 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 + }) + } - // The destination getter are to return this’s request’s destination. - return this[kState].destination + // 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) + } } +} - // 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) +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) - // 1. If this’s request’s referrer is "no-referrer", then return the - // empty string. - if (this[kState].referrer === 'no-referrer') { - return '' - } +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) - // 2. If this’s request’s referrer is "client", then return - // "about:client". - if (this[kState].referrer === 'client') { - return 'about:client' - } +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) - // Return this’s request’s referrer, serialized. - return this[kState].referrer.toString() +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) } - // 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 + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) } - // 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) + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + return webidl.converters.BufferSource(V) + } - // The mode getter steps are to return this’s request’s mode. - return this[kState].mode + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) } - // 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 + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) } - // 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) + return webidl.converters.DOMString(V) +} - // The cache getter steps are to return this’s request’s cache mode. - return this[kState].cache +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) } - // 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 + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V } - // 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) + return webidl.converters.XMLHttpRequestBodyInit(V) +} - // The integrity getter steps are to return this’s request’s integrity - // metadata. - return this[kState].integrity +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 } +]) - // Returns a boolean indicating whether or not request can outlive the - // global in which it was created. - get keepalive () { - webidl.brandCheck(this, Request) +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse +} - // 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 - } +/***/ 9710: +/***/ ((module) => { - // 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) +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} - // 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 - } +/***/ 5523: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get bodyUsed () { - webidl.brandCheck(this, Request) - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } - get duplex () { - webidl.brandCheck(this, Request) +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(7326) +const { getGlobalOrigin } = __nccwpck_require__(5628) +const { performance } = __nccwpck_require__(2987) +const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440) +const assert = __nccwpck_require__(2613) +const { isUint8Array } = __nccwpck_require__(8253) - return 'half' +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = __nccwpck_require__(6982) + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} catch { +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null } - // Returns a clone of request. - clone () { - webidl.brandCheck(this, Request) + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') - // 1. If this is unusable, then throw a TypeError. - if (this.bodyUsed || this.body?.locked) { - throw new TypeError('unusable') - } + // 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)) + } - // 2. Let clonedRequest be the result of cloning this’s request. - const clonedRequest = cloneRequest(this[kState]) + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } - // 3. Let clonedRequestObject be the result of creating a Request object, - // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. - const clonedRequestObject = new Request(kConstruct) - clonedRequestObject[kState] = clonedRequest - clonedRequestObject[kRealm] = this[kRealm] - clonedRequestObject[kHeaders] = new Headers(kConstruct) - clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList - clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] - clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + // 5. Return location. + return location +} - // 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 +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} - // 4. Return clonedRequestObject. - return clonedRequestObject +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' } -mixinBody(Request) +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} -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() +// 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 + } } - request.url = request.urlList[0] - return request + return true } -// 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) +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e } - - // 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 +/** + * @param {string} characters + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false } -}) + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true +} -webidl.converters.Request = webidl.interfaceConverter( - Request -) +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +function isValidHeaderName (potentialValue) { + return isValidHTTPToken(potentialValue) +} -// https://fetch.spec.whatwg.org/#requestinfo -webidl.converters.RequestInfo = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) +/** + * @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 (V instanceof Request) { - return webidl.converters.Request(V) + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false } - return webidl.converters.USVString(V) + return true } -webidl.converters.AbortSignal = webidl.interfaceConverter( - AbortSignal -) +// 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. -// 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 - } -]) + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. -module.exports = { Request, makeRequest } + // 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 + } +} -/***/ 8676: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// 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' +} -const { Headers, HeadersList, fill } = __nccwpck_require__(6349) -const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923) -const util = __nccwpck_require__(3440) -const { kEnumerableProperty } = util -const { - isValidReasonPhrase, - isCancelled, - isAborted, - isBlobLike, - serializeJavascriptValueToJSONString, - isErrorLike, - isomorphicEncode -} = __nccwpck_require__(5523) -const { - redirectStatusSet, - nullBodyStatus, - DOMException -} = __nccwpck_require__(7326) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { FormData } = __nccwpck_require__(3073) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { URLSerializer } = __nccwpck_require__(4322) -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { types } = __nccwpck_require__(9023) +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO -const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream) -const textEncoder = new TextEncoder('utf-8') + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header -// https://fetch.spec.whatwg.org/#response-class -class Response { - // Creates network error Response. - static error () { - // TODO - const relevantRealm = { settingsObject: {} } + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO - // 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 - } + // 2. Let header be a Structured Header whose value is a token. + let header = null - // https://fetch.spec.whatwg.org/#dom-response-json - static json (data, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + // 3. Set header’s value to r’s mode. + header = httpRequest.mode - if (init !== null) { - init = webidl.converters.ResponseInit(init) - } + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) - // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = textEncoder.encode( - serializeJavascriptValueToJSONString(data) - ) + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO - // 2. Let body be the result of extracting bytes. - const body = extractBody(bytes) + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} - // 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 +// 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 - // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). - initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + // 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) + } - // 5. Return responseObject. - return responseObject + // 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) + } } +} - // Creates a redirect Response that redirects to url with status status. - static redirect (url, status = 302) { - const relevantRealm = { settingsObject: {} } +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) +// 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 + } +} - url = webidl.converters.USVString(url) - status = webidl.converters['unsigned short'](status) +// 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' + } +} - // 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 - }) - } +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} - // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatusSet.has(status)) { - throw new RangeError('Invalid status code ' + status) - } +// 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 - // 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 + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) - // 5. Set responseObject’s response’s status to status. - responseObject[kState].status = status + // 2. Let environment be request’s client. - // 6. Let value be parsedURL, serialized and isomorphic encoded. - const value = isomorphicEncode(URLSerializer(parsedURL)) + let referrerSource = null - // 7. Append `Location`/value to responseObject’s response’s header list. - responseObject[kState].headersList.append('location', value) + // 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. - // 8. Return responseObject. - return responseObject - } + const globalOrigin = getGlobalOrigin() - // https://fetch.spec.whatwg.org/#dom-response - constructor (body = null, init = {}) { - if (body !== null) { - body = webidl.converters.BodyInit(body) + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' } - init = webidl.converters.ResponseInit(init) - - // TODO - this[kRealm] = { settingsObject: {} } - - // 1. Set this’s response to a new response. - this[kState] = makeResponse({}) - - // 2. Set this’s headers to a new Headers object with this’s relevant - // Realm, whose header list is this’s response’s header list and guard - // is "response". - this[kHeaders] = new Headers(kConstruct) - this[kHeaders][kGuard] = 'response' - this[kHeaders][kHeadersList] = this[kState].headersList - this[kHeaders][kRealm] = this[kRealm] + // 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 + } - // 3. Let bodyWithType be null. - let bodyWithType = null + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) - // 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. 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) - // 5. Perform initialize a response given this, init, and bodyWithType. - initializeResponse(this, init, bodyWithType) + // 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 } - // 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 - } + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) - // Returns response’s URL, if it has one; otherwise the empty string. - get url () { - webidl.brandCheck(this, Response) + // 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) - const urlList = this[kState].urlList + // 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 + } - // 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 + // 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' + } - if (url === null) { - return '' + // 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 + */ - return URLSerializer(url, true) + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin } +} - // Returns whether response was obtained through a redirect. - get redirected () { - webidl.brandCheck(this, Response) +/** + * @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) - // 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 + // 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' } - // Returns response’s status. - get status () { - webidl.brandCheck(this, Response) + // 3. Set url’s username to the empty string. + url.username = '' - // The status getter steps are to return this’s response’s status. - return this[kState].status - } + // 4. Set url’s password to the empty string. + url.password = '' - // Returns whether response’s status is an ok status. - get ok () { - webidl.brandCheck(this, Response) + // 5. Set url’s fragment to null. + url.hash = '' - // 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 + // 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 = '' } - // Returns response’s status message. - get statusText () { - webidl.brandCheck(this, Response) + // 7. Return url. + return url +} - // The statusText getter steps are to return this’s response’s status - // message. - return this[kState].statusText +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false } - // 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] + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true } - get body () { - webidl.brandCheck(this, Response) + // If scheme is data, return true + if (url.protocol === 'data:') return true - return this[kState].body ? this[kState].body.stream : null - } + // If file, return true + if (url.protocol === 'file:') return true - get bodyUsed () { - webidl.brandCheck(this, Response) + return isOriginPotentiallyTrustworthy(url.origin) - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false - // Returns a clone of response. - clone () { - webidl.brandCheck(this, Response) + const originAsURL = new URL(origin) - // 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.' - }) + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true } - // 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] + // 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 + } - return clonedResponseObject + // If any other, return false + return false } } -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 +/** + * @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 } -}) - -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. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) - // 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. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true } - // 2. Let newResponse be a copy of response, except for its body. - const newResponse = makeResponse({ ...response, body: null }) + // 3. If response is not eligible for integrity validation, return false. + // TODO - // 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. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true } - // 4. Return newResponse. - return newResponse -} + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) -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] : [] - } -} + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo -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' - }) -} + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash -function makeFilteredResponse (response, state) { - state = { - internalResponse: response, - ...state - } + // 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. - 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 + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { return true } - }) -} + } -// 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. + // 7. Return false. + return false +} - // 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. +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i - // 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. +/** + * @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 = [] - 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. + // 2. Let empty be equal to true. + let empty = true - return makeFilteredResponse(response, { - type: 'opaqueredirect', - status: 0, - statusText: '', - headersList: [], - body: null - }) - } else { - assert(false) - } -} + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false -// https://fetch.spec.whatwg.org/#appropriate-network-error -function makeAppropriateNetworkError (fetchParams, err = null) { - // 1. Assert: fetchParams is canceled. - assert(isCancelled(fetchParams)) + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) - // 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 })) -} + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } -// 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.') - } + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() - // 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') + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) } } - // 3. Set response’s response’s status to init["status"]. - if ('status' in init && init.status != null) { - response[kState].status = init.status + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' } - // 4. Set response’s response’s status message to init["statusText"]. - if ('statusText' in init && init.statusText != null) { - response[kState].statusText = init.statusText - } + return result +} - // 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) +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm } - // 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 - }) + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' } + } + return algorithm +} - // 2. Set response's body to body's body. - response[kState].body = body.body +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } - // 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) + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] } } -} -webidl.converters.ReadableStream = webidl.interfaceConverter( - ReadableStream -) - -webidl.converters.FormData = webidl.interfaceConverter( - FormData -) + metadataList.length = pos -webidl.converters.URLSearchParams = webidl.interfaceConverter( - URLSearchParams -) + return metadataList +} -// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit -webidl.converters.XMLHttpRequestBodyInit = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false } - - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } } - if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { - return webidl.converters.BufferSource(V) - } + return true +} - if (util.isFormDataLike(V)) { - return webidl.converters.FormData(V, { strict: false }) +// 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 } - if (V instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V) + // 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 } - return webidl.converters.DOMString(V) + // 3. Return false. + return false } -// https://fetch.spec.whatwg.org/#bodyinit -webidl.converters.BodyInit = function (V) { - if (V instanceof ReadableStream) { - return webidl.converters.ReadableStream(V) - } +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) - // Note: the spec doesn't include async iterables, - // this is an undici extension. - if (V?.[Symbol.asyncIterator]) { - return V - } + return { promise, resolve: res, reject: rej } +} - return webidl.converters.XMLHttpRequestBodyInit(V) +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' } -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 - } -]) +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} -module.exports = { - makeNetworkError, - makeResponse, - makeAppropriateNetworkError, - filterResponse, - Response, - cloneResponse +const normalizeMethodRecord = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' } +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizeMethodRecord, null) -/***/ }), +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizeMethodRecord[method.toLowerCase()] ?? method +} -/***/ 9710: -/***/ ((module) => { +// 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') -module.exports = { - kUrl: Symbol('url'), - kHeaders: Symbol('headers'), - kSignal: Symbol('signal'), - kState: Symbol('state'), - kGuard: Symbol('guard'), - kRealm: Symbol('realm') + // 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 + } -/***/ 5523: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + 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). -const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(7326) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { performance } = __nccwpck_require__(2987) -const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440) -const assert = __nccwpck_require__(2613) -const { isUint8Array } = __nccwpck_require__(8253) + // 4. If object is a platform object, then perform a security + // check, passing: -let supportedHashes = [] + // 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.` + ) + } -// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable -/** @type {import('crypto')|undefined} */ -let crypto + // 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() -try { - crypto = __nccwpck_require__(6982) - const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] - supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) -/* c8 ignore next 3 */ -} catch { -} + // 9. Let len be the length of values. + const len = values.length -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() -} + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } -// 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 - } + // 11. Let pair be the entry in values at index index. + const pair = values[index] - // 2. Let location be the result of extracting header list values given - // `Location` and response’s header list. - let location = response.headersList.get('location') + // 12. Set object’s index to index + 1. + object.index = index + 1 - // 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)) + // 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` } - // 4. If location is a URL whose fragment is null, then set location’s - // fragment to requestFragment. - if (location && !location.hash) { - location.hash = requestFragment + // 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 + } } - // 5. Return location. - return location + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } } -/** @returns {URL} */ -function requestCurrentURL (request) { - return request.urlList[request.urlList.length - 1] -} +/** + * @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. -function requestBadPort (request) { - // 1. Let url be request’s current URL. - const url = requestCurrentURL(request) + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody - // 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. 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 } - // 3. Return allowed. - return 'allowed' + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) + } } -function isErrorLike (object) { - return object instanceof Error || ( - object?.constructor?.name === 'Error' || - object?.constructor?.name === 'DOMException' - ) -} +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream -// 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 - } +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) } - return true + + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) } +const MAXIMUM_ARGUMENT_LENGTH = 65535 + /** - * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 - * @param {number} c + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input */ -function isTokenCharCode (c) { - switch (c) { - case 0x22: - case 0x28: - case 0x29: - case 0x2c: - case 0x2f: - case 0x3a: - case 0x3b: - case 0x3c: - case 0x3d: - case 0x3e: - case 0x3f: - case 0x40: - case 0x5b: - case 0x5c: - case 0x5d: - case 0x7b: - case 0x7d: - // DQUOTE and "(),/:;<=>?@[\]{}" - return false - default: - // VCHAR %x21-7E - return c >= 0x21 && c <= 0x7e +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 {string} characters + * @param {ReadableStreamController} controller */ -function isValidHTTPToken (characters) { - if (characters.length === 0) { - return false - } - for (let i = 0; i < characters.length; ++i) { - if (!isTokenCharCode(characters.charCodeAt(i))) { - return false +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 } } - return true } /** - * @see https://fetch.spec.whatwg.org/#header-name - * @param {string} potentialValue + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input */ -function isValidHeaderName (potentialValue) { - return isValidHTTPToken(potentialValue) +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://fetch.spec.whatwg.org/#header-value - * @param {string} potentialValue + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader */ -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 - } +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 - if ( - potentialValue.includes('\0') || - potentialValue.includes('\r') || - potentialValue.includes('\n') - ) { - return false - } + while (true) { + const { done, value: chunk } = await reader.read() - return true + 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. + } } -// 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. +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object - // 1. Let policy be the result of executing § 8.1 Parse a referrer policy - // from a Referrer-Policy header on actualResponse. + const protocol = url.protocol - // 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(',') + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} - // 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 - } - } +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') } - // 2. If policy is not the empty string, then set request’s referrer policy to policy. - if (policy !== '') { - request.referrerPolicy = policy - } + return url.protocol === 'https:' } -// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check -function crossOriginResourcePolicyCheck () { - // TODO - return 'allowed' -} +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object -// https://fetch.spec.whatwg.org/#concept-cors-check -function corsCheck () { - // TODO - return 'success' -} + const protocol = url.protocol -// https://fetch.spec.whatwg.org/#concept-tao-check -function TAOCheck () { - // TODO - return 'success' + return protocol === 'http:' || protocol === 'https:' } -function appendFetchMetadata (httpRequest) { - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header - // TODO +/** + * 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)) - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header +module.exports = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + normalizeMethodRecord, + parseMetadata +} - // 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 +/***/ 4222: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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 -} +const { types } = __nccwpck_require__(9023) +const { hasOwn, toUSVString } = __nccwpck_require__(5523) -// 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 +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} - // 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) - } +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} - // 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. - } +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(', ')}.` - if (serializedOrigin) { - // 2. Append (`Origin`, serializedOrigin) to request’s header list. - request.headersList.append('origin', serializedOrigin) - } - } + return webidl.errors.exception({ + header: context.prefix, + message + }) } -function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { - // TODO - return performance.now() +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) } -// 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://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] } } -// 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' +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 + }) } } -// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container -function clonePolicyContainer (policyContainer) { - return { - referrerPolicy: policyContainer.referrerPolicy - } +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) } -// 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. +// 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' + } - let referrerSource = null + return 'Object' + } + } +} - // 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. +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound - const globalOrigin = getGlobalOrigin() + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 - if (!globalOrigin || globalOrigin.origin === 'null') { - return 'no-referrer' + // 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: - // 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 - } + // 1. Let lowerBound be 0. + lowerBound = 0 - // 4. Let request’s referrerURL be the result of stripping referrerSource for - // use as a referrer. - let referrerURL = stripURLForReferrer(referrerSource) + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: - // 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) + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 - // 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 + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 } - const areSameOrigin = sameOrigin(request, referrerURL) - const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && - !isURLPotentiallyTrustworthy(request.url) + // 4. Let x be ? ToNumber(V). + let x = Number(V) - // 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) + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } - // 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 - } + // 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. 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' - } + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) - // 3. Return referrerOrigin. - return referrerOrigin + // 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}.` + }) } - 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 + // 4. Return x. + return x } -} -/** - * @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) + // 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. 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' - } + // 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. Set url’s username to the empty string. - url.username = '' + // 3. Return x. + return x + } - // 4. Set url’s password to the empty string. - url.password = '' + // 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 + } - // 5. Set url’s fragment to null. - url.hash = '' + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) - // 6. If the origin-only flag is true, then: - if (originOnly) { - // 1. Set url’s path to « the empty string ». - url.pathname = '' + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) - // 2. Set url’s query to null. - url.search = '' + // 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) } - // 7. Return url. - return url + // 12. Otherwise, return x. + return x } -function isURLPotentiallyTrustworthy (url) { - if (!(url instanceof URL)) { - return false - } +// 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)) - // If child of about, return true - if (url.href === 'about:blank' || url.href === 'about:srcdoc') { - return true + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r } - // 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) + // 3. Otherwise, return r. + return r +} - function isOriginPotentiallyTrustworthy (origin) { - // If origin is explicitly null, return false - if (origin == null || origin === 'null') return false +// 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.` + }) + } - const originAsURL = new URL(origin) + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] - // If secure, return true - if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { - return true + // 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.' + }) } - // 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 + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value)) } - // If any other, return false - return false + return seq } } -/** - * @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 - } +// 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.` + }) + } - // 1. Let parsedMetadata be the result of parsing metadataList. - const parsedMetadata = parseMetadata(metadataList) + // 2. Let result be a new empty instance of record. + const result = {} - // 2. If parsedMetadata is no metadata, return true. - if (parsedMetadata === 'no metadata') { - return true - } + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) - // 3. If response is not eligible for integrity validation, return false. - // TODO + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) - // 4. If parsedMetadata is the empty set, return true. - if (parsedMetadata.length === 0) { - return true - } + // 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]) - // 5. Let metadata be the result of getting the strongest - // metadata from parsedMetadata. - const strongest = getStrongestMetadata(parsedMetadata) - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } - // 6. For each item in metadata: - for (const item of metadata) { - // 1. Let algorithm be the alg component of item. - const algorithm = item.algo + // 5. Return result. + return result + } - // 2. Let expectedValue be the val component of item. - const expectedValue = item.hash + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) - // 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. + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) - // 3. Let actualValue be the result of applying algorithm to bytes. - let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + // 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) - if (actualValue[actualValue.length - 1] === '=') { - if (actualValue[actualValue.length - 2] === '=') { - actualValue = actualValue.slice(0, -2) - } else { - actualValue = actualValue.slice(0, -1) + // 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 } } - // 4. If actualValue is a case-sensitive match for expectedValue, - // return true. - if (compareBase64Mixed(actualValue, expectedValue)) { - return true - } + // 5. Return result. + return result } +} - // 7. Return false. - return false +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 + } } -// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options -// https://www.w3.org/TR/CSP2/#source-list-syntax -// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 -const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} -/** - * @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 = [] + 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.` + }) + } - // 2. Let empty be equal to true. - let empty = true + for (const options of converters) { + const { key, defaultValue, required, converter } = options - // 3. For each token returned by splitting metadata on spaces: - for (const token of metadata.split(' ')) { - // 1. Set empty to false. - empty = false + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } - // 2. Parse token as a hash-with-options. - const parsedToken = parseHashWithOptions.exec(token) + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') - // 3. If token does not parse, continue to the next token. - if ( - parsedToken === null || - parsedToken.groups === undefined || - parsedToken.groups.algo === undefined - ) { - // Note: Chromium blocks the request at this point, but Firefox - // gives a warning that an invalid integrity was given. The - // correct behavior is to ignore these, and subsequently not - // check the integrity of the resource. - continue - } + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } - // 4. Let algorithm be the hash-algo component of token. - const algorithm = parsedToken.groups.algo.toLowerCase() + // 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) - // 5. If algorithm is a hash function recognized by the user - // agent, add the parsed token to result. - if (supportedHashes.includes(algorithm)) { - result.push(parsedToken.groups) + 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 + } } - } - // 4. Return no metadata if empty is true, otherwise return result. - if (empty === true) { - return 'no metadata' + return dict } - - return result } -/** - * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList - */ -function getStrongestMetadata (metadataList) { - // Let algorithm be the algo component of the first item in metadataList. - // Can be sha256 - let algorithm = metadataList[0].algo - // If the algorithm is sha512, then it is the strongest - // and we can return immediately - if (algorithm[3] === '5') { - return algorithm - } - - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i] - // If the algorithm is sha512, then it is the strongest - // and we can break the loop immediately - if (metadata.algo[3] === '5') { - algorithm = 'sha512' - break - // If the algorithm is sha384, then a potential sha256 or sha384 is ignored - } else if (algorithm[3] === '3') { - continue - // algorithm is sha256, check if algorithm is sha384 and if so, set it as - // the strongest - } else if (metadata.algo[3] === '3') { - algorithm = 'sha384' +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V } + + return converter(V) } - return algorithm } -function filterMetadataListByAlgorithm (metadataList, algorithm) { - if (metadataList.length === 1) { - return metadataList +// 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 '' } - let pos = 0 - for (let i = 0; i < metadataList.length; ++i) { - if (metadataList[i].algo === algorithm) { - metadataList[pos++] = metadataList[i] - } + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') } - metadataList.length = pos - - return metadataList + // 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) } -/** - * Compares two base64 strings, allowing for base64url - * in the second string. - * -* @param {string} actualValue always base64 - * @param {string} expectedValue base64 or base64url - * @returns {boolean} - */ -function compareBase64Mixed (actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { - return false - } - for (let i = 0; i < actualValue.length; ++i) { - if (actualValue[i] !== expectedValue[i]) { - if ( - (actualValue[i] === '+' && expectedValue[i] === '-') || - (actualValue[i] === '/' && expectedValue[i] === '_') - ) { - continue - } - return false +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) } } - return true + // 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://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request -function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { - // TODO -} +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString -/** - * @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 - } +// 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. 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 - } + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} - // 3. Return false. - return false +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V } -function createDeferredPromise () { - let res - let rej - const promise = new Promise((resolve, reject) => { - res = resolve - rej = reject - }) +// 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') - return { promise, resolve: res, reject: rej } + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x } -function isAborted (fetchParams) { - return fetchParams.controller.state === 'aborted' -} +// 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') -function isCancelled (fetchParams) { - return fetchParams.controller.state === 'aborted' || - fetchParams.controller.state === 'terminated' + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x } -const normalizeMethodRecord = { - delete: 'DELETE', - DELETE: 'DELETE', - get: 'GET', - GET: 'GET', - head: 'HEAD', - HEAD: 'HEAD', - options: 'OPTIONS', - OPTIONS: 'OPTIONS', - post: 'POST', - POST: 'POST', - put: 'PUT', - PUT: 'PUT' +// 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 } -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizeMethodRecord, null) +// 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) -/** - * @see https://fetch.spec.whatwg.org/#concept-method-normalize - * @param {string} method - */ -function normalizeMethod (method) { - return normalizeMethodRecord[method.toLowerCase()] ?? method + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x } -// 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) +// 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 result is undefined, then throw a TypeError. - if (result === undefined) { - throw new TypeError('Value is not JSON serializable') + // 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. Assert: result is a string. - assert(typeof result === 'string') + // 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 result. - return result + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V } -// 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. +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. - // 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` + // 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] + }) } - // 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 - } + // 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.' + }) } - // 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 - } + // 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. Read all bytes from reader, given successSteps and errorSteps. - try { - const result = await readAllBytes(reader) - successSteps(result) - } catch (e) { - errorSteps(e) - } + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V } -/** @type {ReadableStream} */ -let ReadableStream = globalThis.ReadableStream - -function isReadableStreamLike (stream) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) +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.' + }) } - 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) + // 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.' + }) } - return input.reduce((previous, current) => previous + String.fromCharCode(current), '') -} + // 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 -/** - * @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 - } - } + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V } -/** - * @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) +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) } - // 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. + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) } -} - -/** - * @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:') + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) } - return url.protocol === 'https:' + throw new TypeError(`Could not convert ${V} to a BufferSource.`) } -/** - * @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 +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) - return protocol === 'http:' || protocol === 'https:' -} +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) -/** - * 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)) +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) module.exports = { - isAborted, - isCancelled, - createDeferredPromise, - ReadableStreamFrom, - toUSVString, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - coarsenedSharedCurrentTime, - determineRequestsReferrer, - makePolicyContainer, - clonePolicyContainer, - appendFetchMetadata, - appendRequestOriginHeader, - TAOCheck, - corsCheck, - crossOriginResourcePolicyCheck, - createOpaqueTimingInfo, - setRequestReferrerPolicyOnRedirect, - isValidHTTPToken, - requestBadPort, - requestCurrentURL, - responseURL, - responseLocationURL, - isBlobLike, - isURLPotentiallyTrustworthy, - isValidReasonPhrase, - sameOrigin, - normalizeMethod, - serializeJavascriptValueToJSONString, - makeIterator, - isValidHeaderName, - isValidHeaderValue, - hasOwn, - isErrorLike, - fullyReadBody, - bytesMatch, - isReadableStreamLike, - readableStreamClose, - isomorphicEncode, - isomorphicDecode, - urlIsLocal, - urlHasHttpsScheme, - urlIsHttpHttpsScheme, - readAllBytes, - normalizeMethodRecord, - parseMetadata + webidl } /***/ }), -/***/ 4222: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { types } = __nccwpck_require__(9023) -const { hasOwn, toUSVString } = __nccwpck_require__(5523) - -/** @type {import('../../types/webidl').Webidl} */ -const webidl = {} -webidl.converters = {} -webidl.util = {} -webidl.errors = {} - -webidl.errors.exception = function (message) { - return new TypeError(`${message.header}: ${message.message}`) -} - -webidl.errors.conversionFailed = function (context) { - const plural = context.types.length === 1 ? '' : ' one of' - const message = - `${context.argument} could not be converted to` + - `${plural}: ${context.types.join(', ')}.` - - return webidl.errors.exception({ - header: context.prefix, - message - }) -} - -webidl.errors.invalidArgument = function (context) { - return webidl.errors.exception({ - header: context.prefix, - message: `"${context.value}" is an invalid ${context.type}.` - }) -} - -// https://webidl.spec.whatwg.org/#implements -webidl.brandCheck = function (V, I, opts = undefined) { - if (opts?.strict !== false && !(V instanceof I)) { - throw new TypeError('Illegal invocation') - } else { - return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] - } -} - -webidl.argumentLengthCheck = function ({ length }, min, ctx) { - if (length < min) { - throw webidl.errors.exception({ - message: `${min} argument${min !== 1 ? 's' : ''} required, ` + - `but${length ? ' only' : ''} ${length} found.`, - ...ctx - }) - } -} - -webidl.illegalConstructor = function () { - throw webidl.errors.exception({ - header: 'TypeError', - message: 'Illegal constructor' - }) -} - -// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values -webidl.util.Type = function (V) { - switch (typeof V) { - case 'undefined': return 'Undefined' - case 'boolean': return 'Boolean' - case 'string': return 'String' - case 'symbol': return 'Symbol' - case 'number': return 'Number' - case 'bigint': return 'BigInt' - case 'function': - case 'object': { - if (V === null) { - return 'Null' - } - - return 'Object' - } - } -} - -// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint -webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { - let upperBound - let lowerBound - - // 1. If bitLength is 64, then: - if (bitLength === 64) { - // 1. Let upperBound be 2^53 − 1. - upperBound = Math.pow(2, 53) - 1 - - // 2. If signedness is "unsigned", then let lowerBound be 0. - if (signedness === 'unsigned') { - lowerBound = 0 - } else { - // 3. Otherwise let lowerBound be −2^53 + 1. - lowerBound = Math.pow(-2, 53) + 1 - } - } else if (signedness === 'unsigned') { - // 2. Otherwise, if signedness is "unsigned", then: - - // 1. Let lowerBound be 0. - lowerBound = 0 - - // 2. Let upperBound be 2^bitLength − 1. - upperBound = Math.pow(2, bitLength) - 1 - } else { - // 3. Otherwise: - - // 1. Let lowerBound be -2^bitLength − 1. - lowerBound = Math.pow(-2, bitLength) - 1 +/***/ 396: +/***/ ((module) => { - // 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 +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' } - // 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 + // 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' } +} - // 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) +module.exports = { + getEncoding +} - // 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 - } +/***/ 2160: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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) +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = __nccwpck_require__(165) +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = __nccwpck_require__(6812) +const { webidl } = __nccwpck_require__(4222) +const { kEnumerableProperty } = __nccwpck_require__(3440) + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } } - // 12. Otherwise, return x. - return x -} + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) -// 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)) + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) - // 2. If n < 0, then return -1 × r. - if (n < 0) { - return -1 * r + 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') } - // 3. Otherwise, return r. - return r -} + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) -// 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.` - }) - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) - // 2. Let method be ? GetMethod(V, @@iterator). - /** @type {Generator} */ - const method = V?.[Symbol.iterator]?.() - const seq = [] + blob = webidl.converters.Blob(blob, { strict: false }) - // 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.' - }) - } + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } - // https://webidl.spec.whatwg.org/#create-sequence-from-iterable - while (true) { - const { done, value } = method.next() + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) - if (done) { - break - } + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) - seq.push(converter(value)) + blob = webidl.converters.Blob(blob, { strict: false }) + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) } - return seq + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) } -} - -// 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 = {} + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) - if (!types.isProxy(O)) { - // Object.keys only returns enumerable properties - const keys = Object.keys(O) + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) - for (const key of keys) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) + blob = webidl.converters.Blob(blob, { strict: false }) - // 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]) + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } + /** + * @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 + } - // 5. Return result. - return result + // 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. Let keys be ? O.[[OwnPropertyKeys]](). - const keys = Reflect.ownKeys(O) + // 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. For each key of keys. - for (const key of keys) { - // 1. Let desc be ? O.[[GetOwnProperty]](key). - const desc = Reflect.getOwnPropertyDescriptor(O, key) + // 4. Terminate the algorithm for the read method being processed. + // TODO - // 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) + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) - // 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]) + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } + /** + * @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 } + } - // 5. Return result. - return result + /** + * @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] } -} -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}.` - }) - } + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) - return V + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] } -} -webidl.dictionaryConverter = function (converters) { - return (dictionary) => { - const type = webidl.util.Type(dictionary) - const dict = {} + get onloadend () { + webidl.brandCheck(this, FileReader) - 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.` - }) - } + return this[kEvents].loadend + } - for (const options of converters) { - const { key, defaultValue, required, converter } = options + set onloadend (fn) { + webidl.brandCheck(this, FileReader) - if (required === true) { - if (!hasOwn(dictionary, key)) { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `Missing required key "${key}".` - }) - } - } + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } - let value = dictionary[key] - const hasDefault = hasOwn(options, 'defaultValue') + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } + } - // Only use defaultValue if value is undefined and - // a defaultValue options was provided. - if (hasDefault && value !== null) { - value = value ?? defaultValue - } + get onerror () { + webidl.brandCheck(this, FileReader) - // 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) + return this[kEvents].error + } - 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(', ')}.` - }) - } + set onerror (fn) { + webidl.brandCheck(this, FileReader) - dict[key] = value - } + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) } - return dict + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } } -} -webidl.nullableConverter = function (converter) { - return (V) => { - if (V === null) { - return V - } + get onloadstart () { + webidl.brandCheck(this, FileReader) - return converter(V) + return this[kEvents].loadstart } -} -// 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 '' + 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 + } } - // 2. Let x be ? ToString(V). - if (typeof V === 'symbol') { - throw new TypeError('Could not convert argument of type symbol to string.') + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress } - // 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) -} + set onprogress (fn) { + webidl.brandCheck(this, FileReader) -// 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) + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } - // 2. If the value of any element of x is greater than - // 255, then throw a TypeError. - for (let index = 0; index < x.length; index++) { - if (x.charCodeAt(index) > 255) { - throw new TypeError( - 'Cannot convert argument to a ByteString because the character at ' + - `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` - ) + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null } } - // 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 -} + get onload () { + webidl.brandCheck(this, FileReader) -// https://webidl.spec.whatwg.org/#es-USVString -webidl.converters.USVString = toUSVString + return this[kEvents].load + } -// 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) + set onload (fn) { + webidl.brandCheck(this, FileReader) - // 2. Return the IDL boolean value that is the one that represents - // the same truth value as the ECMAScript Boolean value x. - return x -} + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } -// https://webidl.spec.whatwg.org/#es-any -webidl.converters.any = function (V) { - return V -} + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null + } + } -// 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') + get onabort () { + webidl.brandCheck(this, FileReader) - // 2. Return the IDL long long value that represents - // the same numeric value as x. - return x -} + return this[kEvents].abort + } -// 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') + set onabort (fn) { + webidl.brandCheck(this, FileReader) - // 2. Return the IDL unsigned long long value that - // represents the same numeric value as x. - return x + 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://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') +// 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 - // 2. Return the IDL unsigned long value that - // represents the same numeric value as x. - return x -} +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 + } +}) -// 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) +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) - // 2. Return the IDL unsigned short value that represents - // the same numeric value as x. - return x +module.exports = { + FileReader } -// 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. +/***/ 5976: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // 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] - }) - } +const { webidl } = __nccwpck_require__(4222) - // 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.' - }) - } +const kState = Symbol('ProgressEvent state') - // 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 +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) - // 5. Return the IDL value of type T that is a reference - // to the same object as V. - return V -} + super(type, eventInitDict) -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.' - }) + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } } - // 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.' - }) - } + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) - // 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 + return this[kState].lengthComputable + } - // 4. Return the IDL DataView value that is a reference - // to the same object as V. - return V -} + get loaded () { + webidl.brandCheck(this, ProgressEvent) -// https://webidl.spec.whatwg.org/#BufferSource -webidl.converters.BufferSource = function (V, opts = {}) { - if (types.isAnyArrayBuffer(V)) { - return webidl.converters.ArrayBuffer(V, opts) + return this[kState].loaded } - if (types.isTypedArray(V)) { - return webidl.converters.TypedArray(V, V.constructor) + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total } +} - if (types.isDataView(V)) { - return webidl.converters.DataView(V, opts) +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 } +]) - throw new TypeError(`Could not convert ${V} to a BufferSource.`) +module.exports = { + ProgressEvent } -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.ByteString -) -webidl.converters['sequence>'] = webidl.sequenceConverter( - webidl.converters['sequence'] -) +/***/ }), + +/***/ 6812: +/***/ ((module) => { + -webidl.converters['record'] = webidl.recordConverter( - webidl.converters.ByteString, - webidl.converters.ByteString -) module.exports = { - webidl + 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') } /***/ }), -/***/ 396: -/***/ ((module) => { - - - -/** - * @see https://encoding.spec.whatwg.org/#concept-encoding-get - * @param {string|undefined} label - */ -function getEncoding (label) { - if (!label) { - return 'failure' - } - - // 1. Remove any leading and trailing ASCII whitespace from label. - // 2. If label is an ASCII case-insensitive match for any of the - // labels listed in the table below, then return the - // corresponding encoding; otherwise return failure. - switch (label.trim().toLowerCase()) { - case 'unicode-1-1-utf-8': - case 'unicode11utf8': - case 'unicode20utf8': - case 'utf-8': - case 'utf8': - case 'x-unicode20utf8': - return 'UTF-8' - case '866': - case 'cp866': - case 'csibm866': - case 'ibm866': - return 'IBM866' - case 'csisolatin2': - case 'iso-8859-2': - case 'iso-ir-101': - case 'iso8859-2': - case 'iso88592': - case 'iso_8859-2': - case 'iso_8859-2:1987': - case 'l2': - case 'latin2': - return 'ISO-8859-2' - case 'csisolatin3': - case 'iso-8859-3': - case 'iso-ir-109': - case 'iso8859-3': - case 'iso88593': - case 'iso_8859-3': - case 'iso_8859-3:1988': - case 'l3': - case 'latin3': - return 'ISO-8859-3' - case 'csisolatin4': - case 'iso-8859-4': - case 'iso-ir-110': - case 'iso8859-4': - case 'iso88594': - case 'iso_8859-4': - case 'iso_8859-4:1988': - case 'l4': - case 'latin4': - return 'ISO-8859-4' - case 'csisolatincyrillic': - case 'cyrillic': - case 'iso-8859-5': - case 'iso-ir-144': - case 'iso8859-5': - case 'iso88595': - case 'iso_8859-5': - case 'iso_8859-5:1988': - return 'ISO-8859-5' - case 'arabic': - case 'asmo-708': - case 'csiso88596e': - case 'csiso88596i': - case 'csisolatinarabic': - case 'ecma-114': - case 'iso-8859-6': - case 'iso-8859-6-e': - case 'iso-8859-6-i': - case 'iso-ir-127': - case 'iso8859-6': - case 'iso88596': - case 'iso_8859-6': - case 'iso_8859-6:1987': - return 'ISO-8859-6' - case 'csisolatingreek': - case 'ecma-118': - case 'elot_928': - case 'greek': - case 'greek8': - case 'iso-8859-7': - case 'iso-ir-126': - case 'iso8859-7': - case 'iso88597': - case 'iso_8859-7': - case 'iso_8859-7:1987': - case 'sun_eu_greek': - return 'ISO-8859-7' - case 'csiso88598e': - case 'csisolatinhebrew': - case 'hebrew': - case 'iso-8859-8': - case 'iso-8859-8-e': - case 'iso-ir-138': - case 'iso8859-8': - case 'iso88598': - case 'iso_8859-8': - case 'iso_8859-8:1988': - case 'visual': - return 'ISO-8859-8' - case 'csiso88598i': - case 'iso-8859-8-i': - case 'logical': - return 'ISO-8859-8-I' - case 'csisolatin6': - case 'iso-8859-10': - case 'iso-ir-157': - case 'iso8859-10': - case 'iso885910': - case 'l6': - case 'latin6': - return 'ISO-8859-10' - case 'iso-8859-13': - case 'iso8859-13': - case 'iso885913': - return 'ISO-8859-13' - case 'iso-8859-14': - case 'iso8859-14': - case 'iso885914': - return 'ISO-8859-14' - case 'csisolatin9': - case 'iso-8859-15': - case 'iso8859-15': - case 'iso885915': - case 'iso_8859-15': - case 'l9': - return 'ISO-8859-15' - case 'iso-8859-16': - return 'ISO-8859-16' - case 'cskoi8r': - case 'koi': - case 'koi8': - case 'koi8-r': - case 'koi8_r': - return 'KOI8-R' - case 'koi8-ru': - case 'koi8-u': - return 'KOI8-U' - case 'csmacintosh': - case 'mac': - case 'macintosh': - case 'x-mac-roman': - return 'macintosh' - case 'iso-8859-11': - case 'iso8859-11': - case 'iso885911': - case 'tis-620': - case 'windows-874': - return 'windows-874' - case 'cp1250': - case 'windows-1250': - case 'x-cp1250': - return 'windows-1250' - case 'cp1251': - case 'windows-1251': - case 'x-cp1251': - return 'windows-1251' - case 'ansi_x3.4-1968': - case 'ascii': - case 'cp1252': - case 'cp819': - case 'csisolatin1': - case 'ibm819': - case 'iso-8859-1': - case 'iso-ir-100': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'iso_8859-1:1987': - case 'l1': - case 'latin1': - case 'us-ascii': - case 'windows-1252': - case 'x-cp1252': - return 'windows-1252' - case 'cp1253': - case 'windows-1253': - case 'x-cp1253': - return 'windows-1253' - case 'cp1254': - case 'csisolatin5': - case 'iso-8859-9': - case 'iso-ir-148': - case 'iso8859-9': - case 'iso88599': - case 'iso_8859-9': - case 'iso_8859-9:1989': - case 'l5': - case 'latin5': - case 'windows-1254': - case 'x-cp1254': - return 'windows-1254' - case 'cp1255': - case 'windows-1255': - case 'x-cp1255': - return 'windows-1255' - case 'cp1256': - case 'windows-1256': - case 'x-cp1256': - return 'windows-1256' - case 'cp1257': - case 'windows-1257': - case 'x-cp1257': - return 'windows-1257' - case 'cp1258': - case 'windows-1258': - case 'x-cp1258': - return 'windows-1258' - case 'x-mac-cyrillic': - case 'x-mac-ukrainian': - return 'x-mac-cyrillic' - case 'chinese': - case 'csgb2312': - case 'csiso58gb231280': - case 'gb2312': - case 'gb_2312': - case 'gb_2312-80': - case 'gbk': - case 'iso-ir-58': - case 'x-gbk': - return 'GBK' - case 'gb18030': - return 'gb18030' - case 'big5': - case 'big5-hkscs': - case 'cn-big5': - case 'csbig5': - case 'x-x-big5': - return 'Big5' - case 'cseucpkdfmtjapanese': - case 'euc-jp': - case 'x-euc-jp': - return 'EUC-JP' - case 'csiso2022jp': - case 'iso-2022-jp': - return 'ISO-2022-JP' - case 'csshiftjis': - case 'ms932': - case 'ms_kanji': - case 'shift-jis': - case 'shift_jis': - case 'sjis': - case 'windows-31j': - case 'x-sjis': - return 'Shift_JIS' - case 'cseuckr': - case 'csksc56011987': - case 'euc-kr': - case 'iso-ir-149': - case 'korean': - case 'ks_c_5601-1987': - case 'ks_c_5601-1989': - case 'ksc5601': - case 'ksc_5601': - case 'windows-949': - return 'EUC-KR' - case 'csiso2022kr': - case 'hz-gb-2312': - case 'iso-2022-cn': - case 'iso-2022-cn-ext': - case 'iso-2022-kr': - case 'replacement': - return 'replacement' - case 'unicodefffe': - case 'utf-16be': - return 'UTF-16BE' - case 'csunicode': - case 'iso-10646-ucs-2': - case 'ucs-2': - case 'unicode': - case 'unicodefeff': - case 'utf-16': - case 'utf-16le': - return 'UTF-16LE' - case 'x-user-defined': - return 'x-user-defined' - default: return 'failure' - } -} - -module.exports = { - getEncoding -} - - -/***/ }), - -/***/ 2160: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 165: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent -} = __nccwpck_require__(165) const { kState, kError, kResult, - kEvents, - kAborted + kAborted, + kLastProgressEventFired } = __nccwpck_require__(6812) -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) +const { ProgressEvent } = __nccwpck_require__(5976) +const { getEncoding } = __nccwpck_require__(396) +const { DOMException } = __nccwpck_require__(7326) +const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(4322) +const { types } = __nccwpck_require__(9023) +const { StringDecoder } = __nccwpck_require__(3193) +const { btoa } = __nccwpck_require__(181) -class FileReader extends EventTarget { - constructor () { - super() +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} - 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/#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') } - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer - * @param {import('buffer').Blob} blob - */ - readAsArrayBuffer (blob) { - webidl.brandCheck(this, FileReader) + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + // 3. Set fr’s result to null. + fr[kResult] = null - blob = webidl.converters.Blob(blob, { strict: false }) + // 4. Set fr’s error to null. + fr[kError] = null - // The readAsArrayBuffer(blob) method, when invoked, - // must initiate a read operation for blob with ArrayBuffer. - readOperation(this, blob, 'ArrayBuffer') - } + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() - /** - * @see https://w3c.github.io/FileAPI/#readAsBinaryString - * @param {import('buffer').Blob} blob - */ - readAsBinaryString (blob) { - webidl.brandCheck(this, FileReader) + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] - blob = webidl.converters.Blob(blob, { strict: false }) + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() - // The readAsBinaryString(blob) method, when invoked, - // must initiate a read operation for blob with BinaryString. - readOperation(this, blob, 'BinaryString') - } + // 9. Let isFirstChunk be true. + let isFirstChunk = true - /** - * @see https://w3c.github.io/FileAPI/#readAsDataText - * @param {import('buffer').Blob} blob - * @param {string?} encoding - */ - readAsText (blob, encoding = undefined) { - webidl.brandCheck(this, FileReader) + // 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 - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + // 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) + }) + } - blob = webidl.converters.Blob(blob, { strict: false }) + // 3. Set isFirstChunk to false. + isFirstChunk = false - if (encoding !== undefined) { - encoding = webidl.converters.DOMString(encoding) - } + // 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. - // The readAsText(blob, encoding) method, when invoked, - // must initiate a read operation for blob with Text and encoding. - readOperation(this, blob, 'Text', encoding) - } + // 2. Append bs to bytes. + bytes.push(value) - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL - * @param {import('buffer').Blob} blob - */ - readAsDataURL (blob) { - webidl.brandCheck(this, FileReader) + // 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) + }) + } - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + // 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' - blob = webidl.converters.Blob(blob, { strict: false }) + // 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) - // The readAsDataURL(blob) method, when invoked, must - // initiate a read operation for blob with DataURL. - readOperation(this, blob, 'DataURL') - } + // 4. Else: - /** - * @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 - } + if (fr[kAborted]) { + 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 - } + // 1. Set fr’s result to result. + fr[kResult] = result - // 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 + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: - // 4. Terminate the algorithm for the read method being processed. - // TODO + // 1. Set fr’s error to error. + fr[kError] = error - // 5. Fire a progress event called abort at this. - fireAProgressEvent('abort', this) - - // 6. If this's state is not "loading", fire a progress - // event called loadend at this. - if (this[kState] !== 'loading') { - fireAProgressEvent('loadend', this) - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate - */ - get readyState () { - webidl.brandCheck(this, FileReader) - - switch (this[kState]) { - case 'empty': return this.EMPTY - case 'loading': return this.LOADING - case 'done': return this.DONE - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-result - */ - get result () { - webidl.brandCheck(this, FileReader) - - // The result attribute’s getter, when invoked, must return - // this's result. - return this[kResult] - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-error - */ - get error () { - webidl.brandCheck(this, FileReader) - - // The error attribute’s getter, when invoked, must return - // this's error. - return this[kError] - } - - get onloadend () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].loadend - } - - set onloadend (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].loadend) { - this.removeEventListener('loadend', this[kEvents].loadend) - } - - if (typeof fn === 'function') { - this[kEvents].loadend = fn - this.addEventListener('loadend', fn) - } else { - this[kEvents].loadend = null - } - } - - get onerror () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].error - } - - set onerror (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].error) { - this.removeEventListener('error', this[kEvents].error) - } - - if (typeof fn === 'function') { - this[kEvents].error = fn - this.addEventListener('error', fn) - } else { - this[kEvents].error = null - } - } - - get onloadstart () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].loadstart - } - - set onloadstart (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].loadstart) { - this.removeEventListener('loadstart', this[kEvents].loadstart) - } - - if (typeof fn === 'function') { - this[kEvents].loadstart = fn - this.addEventListener('loadstart', fn) - } else { - this[kEvents].loadstart = null - } - } - - get onprogress () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].progress - } - - set onprogress (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].progress) { - this.removeEventListener('progress', this[kEvents].progress) - } - - if (typeof fn === 'function') { - this[kEvents].progress = fn - this.addEventListener('progress', fn) - } else { - this[kEvents].progress = null - } - } - - get onload () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].load - } - - set onload (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].load) { - this.removeEventListener('load', this[kEvents].load) - } - - if (typeof fn === 'function') { - this[kEvents].load = fn - this.addEventListener('load', fn) - } else { - this[kEvents].load = null - } - } - - get onabort () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].abort - } - - set onabort (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].abort) { - this.removeEventListener('abort', this[kEvents].abort) - } - - if (typeof fn === 'function') { - this[kEvents].abort = fn - this.addEventListener('abort', fn) - } else { - this[kEvents].abort = null - } - } -} - -// https://w3c.github.io/FileAPI/#dom-filereader-empty -FileReader.EMPTY = FileReader.prototype.EMPTY = 0 -// https://w3c.github.io/FileAPI/#dom-filereader-loading -FileReader.LOADING = FileReader.prototype.LOADING = 1 -// https://w3c.github.io/FileAPI/#dom-filereader-done -FileReader.DONE = FileReader.prototype.DONE = 2 - -Object.defineProperties(FileReader.prototype, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors, - readAsArrayBuffer: kEnumerableProperty, - readAsBinaryString: kEnumerableProperty, - readAsText: kEnumerableProperty, - readAsDataURL: kEnumerableProperty, - abort: kEnumerableProperty, - readyState: kEnumerableProperty, - result: kEnumerableProperty, - error: kEnumerableProperty, - onloadstart: kEnumerableProperty, - onprogress: kEnumerableProperty, - onload: kEnumerableProperty, - onabort: kEnumerableProperty, - onerror: kEnumerableProperty, - onloadend: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'FileReader', - writable: false, - enumerable: false, - configurable: true - } -}) - -Object.defineProperties(FileReader, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors -}) - -module.exports = { - FileReader -} - - -/***/ }), - -/***/ 5976: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) - -const kState = Symbol('ProgressEvent state') - -/** - * @see https://xhr.spec.whatwg.org/#progressevent - */ -class ProgressEvent extends Event { - constructor (type, eventInitDict = {}) { - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) - - super(type, eventInitDict) - - this[kState] = { - lengthComputable: eventInitDict.lengthComputable, - loaded: eventInitDict.loaded, - total: eventInitDict.total - } - } - - get lengthComputable () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].lengthComputable - } - - get loaded () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].loaded - } - - get total () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].total - } -} - -webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ - { - key: 'lengthComputable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'loaded', - converter: webidl.converters['unsigned long long'], - defaultValue: 0 - }, - { - key: 'total', - converter: webidl.converters['unsigned long long'], - defaultValue: 0 - }, - { - key: 'bubbles', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'cancelable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'composed', - converter: webidl.converters.boolean, - defaultValue: false - } -]) - -module.exports = { - ProgressEvent -} - - -/***/ }), - -/***/ 6812: -/***/ ((module) => { - - - -module.exports = { - kState: Symbol('FileReader state'), - kResult: Symbol('FileReader result'), - kError: Symbol('FileReader error'), - kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), - kEvents: Symbol('FileReader events'), - kAborted: Symbol('FileReader aborted') -} - - -/***/ }), - -/***/ 165: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - kState, - kError, - kResult, - kAborted, - kLastProgressEventFired -} = __nccwpck_require__(6812) -const { ProgressEvent } = __nccwpck_require__(5976) -const { getEncoding } = __nccwpck_require__(396) -const { DOMException } = __nccwpck_require__(7326) -const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(4322) -const { types } = __nccwpck_require__(9023) -const { StringDecoder } = __nccwpck_require__(3193) -const { btoa } = __nccwpck_require__(181) - -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} - -/** - * @see https://w3c.github.io/FileAPI/#readOperation - * @param {import('./filereader').FileReader} fr - * @param {import('buffer').Blob} blob - * @param {string} type - * @param {string?} encodingName - */ -function readOperation (fr, blob, type, encodingName) { - // 1. If fr’s state is "loading", throw an InvalidStateError - // DOMException. - if (fr[kState] === 'loading') { - throw new DOMException('Invalid state', 'InvalidStateError') - } - - // 2. Set fr’s state to "loading". - fr[kState] = 'loading' - - // 3. Set fr’s result to null. - fr[kResult] = null - - // 4. Set fr’s error to null. - fr[kError] = null - - // 5. Let stream be the result of calling get stream on blob. - /** @type {import('stream/web').ReadableStream} */ - const stream = blob.stream() - - // 6. Let reader be the result of getting a reader from stream. - const reader = stream.getReader() - - // 7. Let bytes be an empty byte sequence. - /** @type {Uint8Array[]} */ - const bytes = [] - - // 8. Let chunkPromise be the result of reading a chunk from - // stream with reader. - let chunkPromise = reader.read() - - // 9. Let isFirstChunk be true. - let isFirstChunk = true - - // 10. In parallel, while true: - // Note: "In parallel" just means non-blocking - // Note 2: readOperation itself cannot be async as double - // reading the body would then reject the promise, instead - // of throwing an error. - ;(async () => { - while (!fr[kAborted]) { - // 1. Wait for chunkPromise to be fulfilled or rejected. - try { - const { done, value } = await chunkPromise - - // 2. If chunkPromise is fulfilled, and isFirstChunk is - // true, queue a task to fire a progress event called - // loadstart at fr. - if (isFirstChunk && !fr[kAborted]) { - queueMicrotask(() => { - fireAProgressEvent('loadstart', fr) - }) - } - - // 3. Set isFirstChunk to false. - isFirstChunk = false - - // 4. If chunkPromise is fulfilled with an object whose - // done property is false and whose value property is - // a Uint8Array object, run these steps: - if (!done && types.isUint8Array(value)) { - // 1. Let bs be the byte sequence represented by the - // Uint8Array object. - - // 2. Append bs to bytes. - bytes.push(value) - - // 3. If roughly 50ms have passed since these steps - // were last invoked, queue a task to fire a - // progress event called progress at fr. - if ( - ( - fr[kLastProgressEventFired] === undefined || - Date.now() - fr[kLastProgressEventFired] >= 50 - ) && - !fr[kAborted] - ) { - fr[kLastProgressEventFired] = Date.now() - queueMicrotask(() => { - fireAProgressEvent('progress', fr) - }) - } - - // 4. Set chunkPromise to the result of reading a - // chunk from stream with reader. - chunkPromise = reader.read() - } else if (done) { - // 5. Otherwise, if chunkPromise is fulfilled with an - // object whose done property is true, queue a task - // to run the following steps and abort this algorithm: - queueMicrotask(() => { - // 1. Set fr’s state to "done". - fr[kState] = 'done' - - // 2. Let result be the result of package data given - // bytes, type, blob’s type, and encodingName. - try { - const result = packageData(bytes, type, blob.type, encodingName) - - // 4. Else: - - if (fr[kAborted]) { - return - } - - // 1. Set fr’s result to result. - fr[kResult] = result - - // 2. Fire a progress event called load at the fr. - fireAProgressEvent('load', fr) - } catch (error) { - // 3. If package data threw an exception error: - - // 1. Set fr’s error to error. - fr[kError] = error - - // 2. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - } + // 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. @@ -59505,1961 +55797,6 @@ function version(uuid) { } var _default = exports["default"] = version; -/***/ }), - -/***/ 7125: -/***/ ((module) => { - - - -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; -}; - - -/***/ }), - -/***/ 3184: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -const usm = __nccwpck_require__(905); - -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; - } -}; - - -/***/ }), - -/***/ 6633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const conversions = __nccwpck_require__(7125); -const utils = __nccwpck_require__(9857); -const Impl = __nccwpck_require__(3184); - -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 } - } -}; - - - -/***/ }), - -/***/ 2686: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -exports.URL = __nccwpck_require__(6633)["interface"]; -exports.serializeURL = __nccwpck_require__(905).serializeURL; -exports.serializeURLOrigin = __nccwpck_require__(905).serializeURLOrigin; -exports.basicURLParse = __nccwpck_require__(905).basicURLParse; -exports.setTheUsername = __nccwpck_require__(905).setTheUsername; -exports.setThePassword = __nccwpck_require__(905).setThePassword; -exports.serializeHost = __nccwpck_require__(905).serializeHost; -exports.serializeInteger = __nccwpck_require__(905).serializeInteger; -exports.parseURL = __nccwpck_require__(905).parseURL; - - -/***/ }), - -/***/ 905: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -const punycode = __nccwpck_require__(4876); -const tr46 = __nccwpck_require__(1552); - -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 }); -}; - - -/***/ }), - -/***/ 9857: -/***/ ((module) => { - - - -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]; -}; - - - /***/ }), /***/ 8264: @@ -61500,14 +55837,6 @@ function wrappy (fn, cb) { } -/***/ }), - -/***/ 2078: -/***/ ((module) => { - -module.exports = eval("require")("encoding"); - - /***/ }), /***/ 2613: @@ -61650,13 +55979,6 @@ module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks") /***/ }), -/***/ 4876: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("punycode"); - -/***/ }), - /***/ 3480: /***/ ((module) => { @@ -67807,317 +62129,6 @@ exports.coerce = { exports.NEVER = parseUtil_js_1.INVALID; -/***/ }), - -/***/ 6220: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - - -// EXPORTS -__nccwpck_require__.d(__webpack_exports__, { - Y: () => (/* binding */ Blob) -}); - -;// CONCATENATED MODULE: ./node_modules/web-streams-polyfill/dist/ponyfill.mjs -/** - * @license - * web-streams-polyfill v4.0.0-beta.3 - * Copyright 2021 Mattias Buelens, Diwank Singh Tomer and other contributors. - * This code is released under the MIT license. - * SPDX-License-Identifier: MIT - */ -const e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function t(){}function r(e){return"object"==typeof e&&null!==e||"function"==typeof e}const o=t;function n(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const a=Promise,i=Promise.prototype.then,l=Promise.resolve.bind(a),s=Promise.reject.bind(a);function u(e){return new a(e)}function c(e){return l(e)}function d(e){return s(e)}function f(e,t,r){return i.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,o)}function h(e,t){b(e,t)}function _(e,t){b(e,void 0,t)}function p(e,t,r){return f(e,t,r)}function m(e){f(e,void 0,o)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function g(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function w(e,t,r){try{return c(g(e,t,r))}catch(e){return d(e)}}class S{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 v=e("[[AbortSteps]]"),R=e("[[ErrorSteps]]"),T=e("[[CancelSteps]]"),q=e("[[PullSteps]]"),C=e("[[ReleaseSteps]]");function E(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),j(e)}(e):B(e,t._storedError)}function P(e,t){return Gt(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?A(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){B(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[C](),t._reader=void 0,e._ownerReadableStream=void 0}function k(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 B(e,t){O(e),A(e,t)}function A(e,t){void 0!==e._closedPromise_reject&&(m(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function j(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const z=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},L=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function F(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function I(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function D(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 N(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!z(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(L(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return z(o)&&0!==o?o:0}function H(e){if(!r(e))return!1;if("function"!=typeof e.getReader)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function x(e){if(!r(e))return!1;if("function"!=typeof e.getWriter)return!1;try{return"boolean"==typeof e.locked}catch(e){return!1}}function V(e,t){if(!Vt(e))throw new TypeError(`${t} is not a ReadableStream.`)}function U(e,t){e._reader._readRequests.push(t)}function G(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function X(e){return e._reader._readRequests.length}function J(e){const t=e._reader;return void 0!==t&&!!K(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");E(this,e),this._readRequests=new S}get closed(){return K(this)?this._closedPromise:d(ee("closed"))}cancel(e){return K(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(ee("cancel"))}read(){if(!K(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(k("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return function(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[q](t)}(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!K(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function K(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function Z(e,t){const r=e._readRequests;e._readRequests=new S,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}}),n(ReadableStreamDefaultReader.prototype.cancel,"cancel"),n(ReadableStreamDefaultReader.prototype.read,"read"),n(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,e.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});class te{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?p(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?p(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;return void 0===e?d(k("iterate")):f(e.read(),(e=>{var t;return this._ongoingPromise=void 0,e.done&&(this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0),e}),(e=>{var t;throw this._ongoingPromise=void 0,this._isFinished=!0,null===(t=this._reader)||void 0===t||t.releaseLock(),this._reader=void 0,e}))}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(void 0===t)return d(k("finish iterating"));if(this._reader=void 0,!this._preventCancel){const r=t.cancel(e);return t.releaseLock(),p(r,(()=>({value:e,done:!0})))}return t.releaseLock(),c({value:e,done:!0})}}const re={next(){return oe(this)?this._asyncIteratorImpl.next():d(ne("next"))},return(e){return oe(this)?this._asyncIteratorImpl.return(e):d(ne("return"))}};function oe(e){if(!r(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof te}catch(e){return!1}}function ne(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}"symbol"==typeof e.asyncIterator&&Object.defineProperty(re,e.asyncIterator,{value(){return this},writable:!0,configurable:!0});const ae=Number.isNaN||function(e){return e!=e};function ie(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}function le(e){const t=function(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return ie(n,0,e,t,o),n}(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function se(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ue(e,t,r){if("number"!=typeof(o=r)||ae(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 ce(e){e._queue=new S,e._queueTotalSize=0}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!fe(this))throw Be("view");return this._view}respond(e){if(!fe(this))throw Be("respond");if($(e,1,"respond"),e=N(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");this._view.buffer,function(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=r.buffer,qe(e,t)}(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!fe(this))throw Be("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");e.buffer,function(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=t.buffer,qe(e,o)}(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),n(ReadableStreamBYOBRequest.prototype.respond,"respond"),n(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,e.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!de(this))throw Ae("byobRequest");return function(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}(this)}get desiredSize(){if(!de(this))throw Ae("desiredSize");return ke(this)}close(){if(!de(this))throw Ae("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`);!function(e){const t=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==t._state)return;if(e._queueTotalSize>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){if(e._pendingPullIntos.peek().bytesFilled>0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Pe(e,t),t}}Ee(e),Xt(t)}(this)}enqueue(e){if(!de(this))throw Ae("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`);!function(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const o=t.buffer,n=t.byteOffset,a=t.byteLength,i=o;if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();t.buffer,0,Re(e),t.buffer=t.buffer,"none"===t.readerType&&ge(e,t)}if(J(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;We(e,t._readRequests.shift())}}(e),0===X(r))me(e,i,n,a);else{e._pendingPullIntos.length>0&&Ce(e);G(r,new Uint8Array(i,n,a),!1)}else Le(r)?(me(e,i,n,a),Te(e)):me(e,i,n,a);be(e)}(this,e)}error(e){if(!de(this))throw Ae("error");Pe(this,e)}[T](e){he(this),ce(this);const t=this._cancelAlgorithm(e);return Ee(this),t}[q](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void We(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,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}U(t,e),be(this)}[C](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new S,this._pendingPullIntos.push(e)}}}function de(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function be(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(J(t)&&X(t)>0)return!0;if(Le(t)&&ze(t)>0)return!0;if(ke(e)>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,be(e)),null)),(t=>(Pe(e,t),null)))}function he(e){Re(e),e._pendingPullIntos=new S}function _e(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=pe(t);"default"===t.readerType?G(e,o,r):function(e,t,r){const o=e._reader._readIntoRequests.shift();r?o._closeSteps(t):o._chunkSteps(t)}(e,o,r)}function pe(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function me(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function ye(e,t,r,o){let n;try{n=t.slice(r,r+o)}catch(t){throw Pe(e,t),t}me(e,n,0,o)}function ge(e,t){t.bytesFilled>0&&ye(e,t.buffer,t.byteOffset,t.bytesFilled),Ce(e)}function we(e,t){const r=t.elementSize,o=t.bytesFilled-t.bytesFilled%r,n=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),a=t.bytesFilled+n,i=a-a%r;let l=n,s=!1;i>o&&(l=i-t.bytesFilled,s=!0);const u=e._queue;for(;l>0;){const r=u.peek(),o=Math.min(l,r.byteLength),n=t.byteOffset+t.bytesFilled;ie(t.buffer,n,r.buffer,r.byteOffset,o),r.byteLength===o?u.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Se(e,o,t),l-=o}return s}function Se(e,t,r){r.bytesFilled+=t}function ve(e){0===e._queueTotalSize&&e._closeRequested?(Ee(e),Xt(e._controlledReadableByteStream)):be(e)}function Re(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Te(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();we(e,t)&&(Ce(e),_e(e._controlledReadableByteStream,t))}}function qe(e,t){const r=e._pendingPullIntos.peek();Re(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&Ce(e);const r=e._controlledReadableByteStream;if(Le(r))for(;ze(r)>0;)_e(r,Ce(e))}(e,r):function(e,t,r){if(Se(0,t,r),"none"===r.readerType)return ge(e,r),void Te(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;ye(e,r.buffer,t-o,o)}r.bytesFilled-=o,_e(e._controlledReadableByteStream,r),Te(e)}(e,t,r),be(e)}function Ce(e){return e._pendingPullIntos.shift()}function Ee(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Pe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(he(e),ce(e),Ee(e),Jt(r,t))}function We(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,ve(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function ke(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Oe(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");!function(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,ce(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new S,e._readableStreamController=t,b(c(r()),(()=>(t._started=!0,be(t),null)),(e=>(Pe(t,e),null)))}(e,o,n,a,i,r,l)}function Be(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ae(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function je(e,t){e._reader._readIntoRequests.push(t)}function ze(e){return e._reader._readIntoRequests.length}function Le(e){const t=e._reader;return void 0!==t&&!!Fe(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableByteStreamController.prototype.close,"close"),n(ReadableByteStreamController.prototype.enqueue,"enqueue"),n(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,e.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),V(e,"First parameter"),Ut(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!de(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");E(this,e),this._readIntoRequests=new S}get closed(){return Fe(this)?this._closedPromise:d(De("closed"))}cancel(e){return Fe(this)?void 0===this._ownerReadableStream?d(k("cancel")):P(this,e):d(De("cancel"))}read(e){if(!Fe(this))return d(De("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(e.buffer,void 0===this._ownerReadableStream)return d(k("read from"));let t,r;const o=u(((e,o)=>{t=e,r=o}));return function(e,t,r){const o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?r._errorSteps(o._storedError):function(e,t,r){const o=e._controlledReadableByteStream;let n=1;t.constructor!==DataView&&(n=t.constructor.BYTES_PER_ELEMENT);const a=t.constructor,i=t.buffer,l={buffer:i,bufferByteLength:i.byteLength,byteOffset:t.byteOffset,byteLength:t.byteLength,bytesFilled:0,elementSize:n,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(l),void je(o,r);if("closed"!==o._state){if(e._queueTotalSize>0){if(we(e,l)){const t=pe(l);return ve(e),void r._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Pe(e,t),void r._errorSteps(t)}}e._pendingPullIntos.push(l),je(o,r),be(e)}else{const e=new a(l.buffer,l.byteOffset,0);r._closeSteps(e)}}(o._readableStreamController,t,r)}(this,e,{_chunkSteps:e=>t({value:e,done:!1}),_closeSteps:e=>t({value:e,done:!0}),_errorSteps:e=>r(e)}),o}releaseLock(){if(!Fe(this))throw De("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Ie(e,t)}(this)}}function Fe(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function Ie(e,t){const r=e._readIntoRequests;e._readIntoRequests=new S,r.forEach((e=>{e._errorSteps(t)}))}function De(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function $e(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ae(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function Me(e){const{size:t}=e;return t||(()=>1)}function Ye(e,t){F(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:Qe(o,`${t} has member 'size' that`)}}function Qe(e,t){return I(e,t),t=>Y(e(t))}function Ne(e,t,r){return I(e,r),r=>w(e,t,[r])}function He(e,t,r){return I(e,r),()=>w(e,t,[])}function xe(e,t,r){return I(e,r),r=>g(e,t,[r])}function Ve(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),n(ReadableStreamBYOBReader.prototype.cancel,"cancel"),n(ReadableStreamBYOBReader.prototype.read,"read"),n(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,e.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const Ue="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(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:Ne(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:He(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:xe(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:Ve(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");var n;(n=this)._state="writable",n._storedError=void 0,n._writer=void 0,n._writableStreamController=void 0,n._writeRequests=new S,n._inFlightWriteRequest=void 0,n._closeRequest=void 0,n._inFlightCloseRequest=void 0,n._pendingAbortRequest=void 0,n._backpressure=!1;if(void 0!==o.type)throw new RangeError("Invalid type is specified");const a=Me(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);!function(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,ce(t),t._abortReason=void 0,t._abortController=function(){if(Ue)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=bt(t);nt(e,s);const u=r();b(c(u),(()=>(t._started=!0,dt(t),null)),(r=>(t._started=!0,Ze(e,r),null)))}(e,n,a,i,l,s,r,o)}(this,o,$e(r,1),a)}get locked(){if(!Ge(this))throw _t("locked");return Xe(this)}abort(e){return Ge(this)?Xe(this)?d(new TypeError("Cannot abort a stream that already has a writer")):Je(this,e):d(_t("abort"))}close(){return Ge(this)?Xe(this)?d(new TypeError("Cannot close a stream that already has a writer")):rt(this)?d(new TypeError("Cannot close an already-closing stream")):Ke(this):d(_t("close"))}getWriter(){if(!Ge(this))throw _t("getWriter");return new WritableStreamDefaultWriter(this)}}function Ge(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function Xe(e){return void 0!==e._writer}function Je(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||et(e,t),a}function Ke(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&&Et(o),ue(n=e._writableStreamController,lt,0),dt(n),r}function Ze(e,t){"writable"!==e._state?tt(e):et(e,t)}function et(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&it(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&tt(e)}function tt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new S,void 0===e._pendingAbortRequest)return void ot(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void ot(e);b(e._writableStreamController[v](r._reason),(()=>(r._resolve(),ot(e),null)),(t=>(r._reject(t),ot(e),null)))}function rt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function ot(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&St(t,e._storedError)}function nt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Rt(e)}(r):Et(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),n(WritableStream.prototype.abort,"abort"),n(WritableStream.prototype.close,"close"),n(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStream.prototype,e.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),function(e,t){if(!Ge(e))throw new TypeError(`${t} is not a WritableStream.`)}(e,"First parameter"),Xe(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)!rt(e)&&e._backpressure?Rt(this):qt(this),gt(this);else if("erroring"===t)Tt(this,e._storedError),gt(this);else if("closed"===t)qt(this),gt(r=this),vt(r);else{const t=e._storedError;Tt(this,t),wt(this,t)}var r}get closed(){return at(this)?this._closedPromise:d(mt("closed"))}get desiredSize(){if(!at(this))throw mt("desiredSize");if(void 0===this._ownerWritableStream)throw yt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return ct(t._writableStreamController)}(this)}get ready(){return at(this)?this._readyPromise:d(mt("ready"))}abort(e){return at(this)?void 0===this._ownerWritableStream?d(yt("abort")):function(e,t){return Je(e._ownerWritableStream,t)}(this,e):d(mt("abort"))}close(){if(!at(this))return d(mt("close"));const e=this._ownerWritableStream;return void 0===e?d(yt("close")):rt(e)?d(new TypeError("Cannot close an already-closing stream")):Ke(this._ownerWritableStream)}releaseLock(){if(!at(this))throw mt("releaseLock");void 0!==this._ownerWritableStream&&function(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");it(e,r),function(e,t){"pending"===e._closedPromiseState?St(e,t):function(e,t){wt(e,t)}(e,t)}(e,r),t._writer=void 0,e._ownerWritableStream=void 0}(this)}write(e){return at(this)?void 0===this._ownerWritableStream?d(yt("write to")):function(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return ft(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(yt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(rt(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{ue(e,t,r)}catch(t){return void ft(e,t)}const o=e._controlledWritableStream;if(!rt(o)&&"writable"===o._state){nt(o,bt(e))}dt(e)}(o,t,n),i}(this,e):d(mt("write"))}}function at(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function it(e,t){"pending"===e._readyPromiseState?Ct(e,t):function(e,t){Tt(e,t)}(e,t)}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}}),n(WritableStreamDefaultWriter.prototype.abort,"abort"),n(WritableStreamDefaultWriter.prototype.close,"close"),n(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),n(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof e.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,e.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const lt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!st(this))throw pt("abortReason");return this._abortReason}get signal(){if(!st(this))throw pt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e){if(!st(this))throw pt("error");"writable"===this._controlledWritableStream._state&&ht(this,e)}[v](e){const t=this._abortAlgorithm(e);return ut(this),t}[R](){ce(this)}}function st(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function ut(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ct(e){return e._strategyHWM-e._queueTotalSize}function dt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void tt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===lt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),se(e);const r=e._closeAlgorithm();ut(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),Ze(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);b(e._writeAlgorithm(t),(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(se(e),!rt(r)&&"writable"===t){const t=bt(e);nt(r,t)}return dt(e),null}),(t=>("writable"===r._state&&ut(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Ze(e,t)}(r,t),null)))}(e,r)}function ft(e,t){"writable"===e._controlledWritableStream._state&&ht(e,t)}function bt(e){return ct(e)<=0}function ht(e,t){const r=e._controlledWritableStream;ut(e),et(r,t)}function _t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function pt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function mt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function yt(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 wt(e,t){gt(e),St(e,t)}function St(e,t){void 0!==e._closedPromise_reject&&(m(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 Rt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Tt(e,t){Rt(e),Ct(e,t)}function qt(e){Rt(e),Et(e)}function Ct(e,t){void 0!==e._readyPromise_reject&&(m(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Et(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 e.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,e.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Pt="undefined"!=typeof DOMException?DOMException:void 0;const Wt=function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;try{return new e,!0}catch(e){return!1}}(Pt)?Pt:function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function kt(e,t,r,o,n,a){const i=e.getReader(),l=t.getWriter();Vt(e)&&(e._disturbed=!0);let s,_,g,w=!1,S=!1,v="readable",R="writable",T=!1,q=!1;const C=u((e=>{g=e}));let E=Promise.resolve(void 0);return u(((P,W)=>{let k;function O(){if(w)return;const e=u(((e,t)=>{!function r(o){o?e():f(function(){if(w)return c(!0);return f(l.ready,(()=>f(i.read(),(e=>!!e.done||(E=l.write(e.value),m(E),!1)))))}(),r,t)}(!1)}));m(e)}function B(){return v="closed",r?L():z((()=>(Ge(t)&&(T=rt(t),R=t._state),T||"closed"===R?c(void 0):"erroring"===R||"errored"===R?d(_):(T=!0,l.close()))),!1,void 0),null}function A(e){return w||(v="errored",s=e,o?L(!0,e):z((()=>l.abort(e)),!0,e)),null}function j(e){return S||(R="errored",_=e,n?L(!0,e):z((()=>i.cancel(e)),!0,e)),null}if(void 0!==a&&(k=()=>{const e=void 0!==a.reason?a.reason:new Wt("Aborted","AbortError"),t=[];o||t.push((()=>"writable"===R?l.abort(e):c(void 0))),n||t.push((()=>"readable"===v?i.cancel(e):c(void 0))),z((()=>Promise.all(t.map((e=>e())))),!0,e)},a.aborted?k():a.addEventListener("abort",k)),Vt(e)&&(v=e._state,s=e._storedError),Ge(t)&&(R=t._state,_=t._storedError,T=rt(t)),Vt(e)&&Ge(t)&&(q=!0,g()),"errored"===v)A(s);else if("erroring"===R||"errored"===R)j(_);else if("closed"===v)B();else if(T||"closed"===R){const e=new TypeError("the destination writable stream closed before all data could be piped to it");n?L(!0,e):z((()=>i.cancel(e)),!0,e)}function z(e,t,r){function o(){return"writable"!==R||T?n():h(function(){let e;return c(function t(){if(e!==E)return e=E,p(E,t,t)}())}(),n),null}function n(){return e?b(e(),(()=>F(t,r)),(e=>F(!0,e))):F(t,r),null}w||(w=!0,q?o():h(C,o))}function L(e,t){z(void 0,e,t)}function F(e,t){return S=!0,l.releaseLock(),i.releaseLock(),void 0!==a&&a.removeEventListener("abort",k),e?W(t):P(void 0),null}w||(b(i.closed,B,A),b(l.closed,(function(){return S||(R="closed"),null}),j)),q?O():y((()=>{q=!0,g(),O()}))}))}function Ot(e,t){return function(e){try{return e.getReader({mode:"byob"}).releaseLock(),!0}catch(e){return!1}}(e)?function(e){let t,r,o,n,a,i=e.getReader(),l=!1,s=!1,d=!1,f=!1,h=!1,p=!1;const m=u((e=>{a=e}));function y(e){_(e.closed,(t=>(e!==i||(o.error(t),n.error(t),h&&p||a(void 0)),null)))}function g(){l&&(i.releaseLock(),i=e.getReader(),y(i),l=!1),b(i.read(),(e=>{var t,r;if(d=!1,f=!1,e.done)return h||o.close(),p||n.close(),null===(t=o.byobRequest)||void 0===t||t.respond(0),null===(r=n.byobRequest)||void 0===r||r.respond(0),h&&p||a(void 0),null;const l=e.value,u=l;let c=l;if(!h&&!p)try{c=le(l)}catch(e){return o.error(e),n.error(e),a(i.cancel(e)),null}return h||o.enqueue(u),p||n.enqueue(c),s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function w(t,r){l||(i.releaseLock(),i=e.getReader({mode:"byob"}),y(i),l=!0);const u=r?n:o,c=r?o:n;b(i.read(t),(e=>{var t;d=!1,f=!1;const o=r?p:h,n=r?h:p;if(e.done){o||u.close(),n||c.close();const r=e.value;return void 0!==r&&(o||u.byobRequest.respondWithNewView(r),n||null===(t=c.byobRequest)||void 0===t||t.respond(0)),o&&n||a(void 0),null}const l=e.value;if(n)o||u.byobRequest.respondWithNewView(l);else{let e;try{e=le(l)}catch(e){return u.error(e),c.error(e),a(i.cancel(e)),null}o||u.byobRequest.respondWithNewView(l),c.enqueue(e)}return s=!1,d?S():f&&v(),null}),(()=>(s=!1,null)))}function S(){if(s)return d=!0,c(void 0);s=!0;const e=o.byobRequest;return null===e?g():w(e.view,!1),c(void 0)}function v(){if(s)return f=!0,c(void 0);s=!0;const e=n.byobRequest;return null===e?g():w(e.view,!0),c(void 0)}function R(e){if(h=!0,t=e,p){const e=[t,r],o=i.cancel(e);a(o)}return m}function T(e){if(p=!0,r=e,h){const e=[t,r],o=i.cancel(e);a(o)}return m}const q=new ReadableStream({type:"bytes",start(e){o=e},pull:S,cancel:R}),C=new ReadableStream({type:"bytes",start(e){n=e},pull:v,cancel:T});return y(i),[q,C]}(e):function(e,t){const r=e.getReader();let o,n,a,i,l,s=!1,d=!1,f=!1,h=!1;const p=u((e=>{l=e}));function m(){return s?(d=!0,c(void 0)):(s=!0,b(r.read(),(e=>{if(d=!1,e.done)return f||a.close(),h||i.close(),f&&h||l(void 0),null;const t=e.value,r=t,o=t;return f||a.enqueue(r),h||i.enqueue(o),s=!1,d&&m(),null}),(()=>(s=!1,null))),c(void 0))}function y(e){if(f=!0,o=e,h){const e=[o,n],t=r.cancel(e);l(t)}return p}function g(e){if(h=!0,n=e,f){const e=[o,n],t=r.cancel(e);l(t)}return p}const w=new ReadableStream({start(e){a=e},pull:m,cancel:y}),S=new ReadableStream({start(e){i=e},pull:m,cancel:g});return _(r.closed,(e=>(a.error(e),i.error(e),f&&h||l(void 0),null))),[w,S]}(e)}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Bt(this))throw Dt("desiredSize");return Lt(this)}close(){if(!Bt(this))throw Dt("close");if(!Ft(this))throw new TypeError("The stream is not in a state that permits close");!function(e){if(!Ft(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(jt(e),Xt(t))}(this)}enqueue(e){if(!Bt(this))throw Dt("enqueue");if(!Ft(this))throw new TypeError("The stream is not in a state that permits enqueue");return function(e,t){if(!Ft(e))return;const r=e._controlledReadableStream;if(Ut(r)&&X(r)>0)G(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw zt(e,t),t}try{ue(e,t,r)}catch(t){throw zt(e,t),t}}At(e)}(this,e)}error(e){if(!Bt(this))throw Dt("error");zt(this,e)}[T](e){ce(this);const t=this._cancelAlgorithm(e);return jt(this),t}[q](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=se(this);this._closeRequested&&0===this._queue.length?(jt(this),Xt(t)):At(this),e._chunkSteps(r)}else U(t,e),At(this)}[C](){}}function Bt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function At(e){const t=function(e){const t=e._controlledReadableStream;if(!Ft(e))return!1;if(!e._started)return!1;if(Ut(t)&&X(t)>0)return!0;if(Lt(e)>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,At(e)),null)),(t=>(zt(e,t),null)))}function jt(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function zt(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(ce(e),jt(e),Jt(r,t))}function Lt(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ft(e){return!e._closeRequested&&"readable"===e._controlledReadableStream._state}function It(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),function(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,ce(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,At(t),null)),(e=>(zt(t,e),null)))}(e,n,a,i,l,r,o)}function Dt(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function $t(e,t,r){return I(e,r),r=>w(e,t,[r])}function Mt(e,t,r){return I(e,r),r=>w(e,t,[r])}function Yt(e,t,r){return I(e,r),r=>g(e,t,[r])}function Qt(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Nt(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ht(e,t){F(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}}function xt(e,t){F(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),function(e,t){if(!H(e))throw new TypeError(`${t} is not a ReadableStream.`)}(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),function(e,t){if(!x(e))throw new TypeError(`${t} is not a WritableStream.`)}(o,`${t} has member 'writable' that`),{readable:r,writable:o}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),n(ReadableStreamDefaultController.prototype.close,"close"),n(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),n(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,e.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:D(e,"First parameter");const r=Ye(t,"Second parameter"),o=function(e,t){F(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:N(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:$t(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:Mt(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:Yt(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Qt(l,`${t} has member 'type' that`)}}(e,"First parameter");var n;if((n=this)._state="readable",n._reader=void 0,n._storedError=void 0,n._disturbed=!1,"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");Oe(this,o,$e(r,0))}else{const e=Me(r);It(this,o,$e(r,1),e)}}get locked(){if(!Vt(this))throw Kt("locked");return Ut(this)}cancel(e){return Vt(this)?Ut(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Gt(this,e):d(Kt("cancel"))}getReader(e){if(!Vt(this))throw Kt("getReader");return void 0===function(e,t){F(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Nt(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?new ReadableStreamDefaultReader(this):function(e){return new ReadableStreamBYOBReader(e)}(this)}pipeThrough(e,t={}){if(!H(this))throw Kt("pipeThrough");$(e,1,"pipeThrough");const r=xt(e,"First parameter"),o=Ht(t,"Second parameter");if(this.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(r.writable.locked)throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return m(kt(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!H(this))return d(Kt("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!x(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Ht(t,"Second parameter")}catch(e){return d(e)}return this.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):e.locked?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):kt(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!H(this))throw Kt("tee");if(this.locked)throw new TypeError("Cannot tee a stream that already has a reader");return Ot(this)}values(e){if(!H(this))throw Kt("values");return function(e,t){const r=e.getReader(),o=new te(r,t),n=Object.create(re);return n._asyncIteratorImpl=o,n}(this,function(e,t){F(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}}function Vt(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Ut(e){return void 0!==e._reader}function Gt(e,r){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Xt(e);const o=e._reader;if(void 0!==o&&Fe(o)){const e=o._readIntoRequests;o._readIntoRequests=new S,e.forEach((e=>{e._closeSteps(void 0)}))}return p(e._readableStreamController[T](r),t)}function Xt(e){e._state="closed";const t=e._reader;if(void 0!==t&&(j(t),K(t))){const e=t._readRequests;t._readRequests=new S,e.forEach((e=>{e._closeSteps()}))}}function Jt(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(A(r,t),K(r)?Z(r,t):Ie(r,t))}function Kt(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Zt(e,t){F(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}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}}),n(ReadableStream.prototype.cancel,"cancel"),n(ReadableStream.prototype.getReader,"getReader"),n(ReadableStream.prototype.pipeThrough,"pipeThrough"),n(ReadableStream.prototype.pipeTo,"pipeTo"),n(ReadableStream.prototype.tee,"tee"),n(ReadableStream.prototype.values,"values"),"symbol"==typeof e.toStringTag&&Object.defineProperty(ReadableStream.prototype,e.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof e.asyncIterator&&Object.defineProperty(ReadableStream.prototype,e.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const er=e=>e.byteLength;n(er,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Zt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!rr(this))throw tr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!rr(this))throw tr("size");return er}}function tr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function rr(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,e.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const or=()=>1;n(or,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Zt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!ar(this))throw nr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!ar(this))throw nr("size");return or}}function nr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function ar(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function ir(e,t,r){return I(e,r),r=>w(e,t,[r])}function lr(e,t,r){return I(e,r),r=>g(e,t,[r])}function sr(e,t,r){return I(e,r),(r,o)=>w(e,t,[r,o])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof e.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,e.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=Ye(t,"Second parameter"),n=Ye(r,"Third parameter"),a=function(e,t){F(e,t);const r=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,n=null==e?void 0:e.start,a=null==e?void 0:e.transform,i=null==e?void 0:e.writableType;return{flush:void 0===r?void 0:ir(r,e,`${t} has member 'flush' that`),readableType:o,start:void 0===n?void 0:lr(n,e,`${t} has member 'start' that`),transform:void 0===a?void 0:sr(a,e,`${t} has member 'transform' that`),writableType:i}}(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=$e(n,0),l=Me(n),s=$e(o,1),f=Me(o);let b;!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 p(e._backpressureChangePromise,(()=>{if("erroring"===(Ge(e._writable)?e._writable._state:e._writableState))throw Ge(e._writable)?e._writable._storedError:e._writableStoredError;return pr(r,t)}))}return pr(r,t)}(e,t)}function s(t){return function(e,t){return cr(e,t),c(void 0)}(e,t)}function u(){return function(e){const t=e._transformStreamController,r=t._flushAlgorithm();return hr(t),p(r,(()=>{if("errored"===e._readableState)throw e._readableStoredError;gr(e)&&wr(e)}),(t=>{throw cr(e,t),e._readableStoredError}))}(e)}function d(){return function(e){return fr(e,!1),e._backpressureChangePromise}(e)}function f(t){return dr(e,t),c(void 0)}e._writableState="writable",e._writableStoredError=void 0,e._writableHasInFlightOperation=!1,e._writableStarted=!1,e._writable=function(e,t,r,o,n,a,i){return new WritableStream({start(r){e._writableController=r;try{const t=r.signal;void 0!==t&&t.addEventListener("abort",(()=>{"writable"===e._writableState&&(e._writableState="erroring",t.reason&&(e._writableStoredError=t.reason))}))}catch(e){}return p(t(),(()=>(e._writableStarted=!0,Cr(e),null)),(t=>{throw e._writableStarted=!0,Rr(e,t),t}))},write:t=>(function(e){e._writableHasInFlightOperation=!0}(e),p(r(t),(()=>(function(e){e._writableHasInFlightOperation=!1}(e),Cr(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,Rr(e,t)}(e,t),t}))),close:()=>(function(e){e._writableHasInFlightOperation=!0}(e),p(o(),(()=>(function(e){e._writableHasInFlightOperation=!1;"erroring"===e._writableState&&(e._writableStoredError=void 0);e._writableState="closed"}(e),null)),(t=>{throw function(e,t){e._writableHasInFlightOperation=!1,e._writableState,Rr(e,t)}(e,t),t}))),abort:t=>(e._writableState="errored",e._writableStoredError=t,n(t))},{highWaterMark:a,size:i})}(e,i,l,u,s,r,o),e._readableState="readable",e._readableStoredError=void 0,e._readableCloseRequested=!1,e._readablePulling=!1,e._readable=function(e,t,r,o,n,a){return new ReadableStream({start:r=>(e._readableController=r,t().catch((t=>{Sr(e,t)}))),pull:()=>(e._readablePulling=!0,r().catch((t=>{Sr(e,t)}))),cancel:t=>(e._readableState="closed",o(t))},{highWaterMark:n,size:a})}(e,i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fr(e,!0),e._transformStreamController=void 0}(this,u((e=>{b=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return _r(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);!function(e,t,r,o){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o}(e,r,o,n)}(this,a),void 0!==a.start?b(a.start(this._transformStreamController)):b(void 0)}get readable(){if(!ur(this))throw yr("readable");return this._readable}get writable(){if(!ur(this))throw yr("writable");return this._writable}}function ur(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function cr(e,t){Sr(e,t),dr(e,t)}function dr(e,t){hr(e._transformStreamController),function(e,t){e._writableController.error(t);"writable"===e._writableState&&Tr(e,t)}(e,t),e._backpressure&&fr(e,!1)}function fr(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 e.toStringTag&&Object.defineProperty(TransformStream.prototype,e.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!br(this))throw mr("desiredSize");return vr(this._controlledTransformStream)}enqueue(e){if(!br(this))throw mr("enqueue");_r(this,e)}error(e){if(!br(this))throw mr("error");var t;t=e,cr(this._controlledTransformStream,t)}terminate(){if(!br(this))throw mr("terminate");!function(e){const t=e._controlledTransformStream;gr(t)&&wr(t);const r=new TypeError("TransformStream terminated");dr(t,r)}(this)}}function br(e){return!!r(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0}function _r(e,t){const r=e._controlledTransformStream;if(!gr(r))throw new TypeError("Readable side is not in a state that permits enqueue");try{!function(e,t){e._readablePulling=!1;try{e._readableController.enqueue(t)}catch(t){throw Sr(e,t),t}}(r,t)}catch(e){throw dr(r,e),r._readableStoredError}const o=function(e){return!function(e){if(!gr(e))return!1;if(e._readablePulling)return!0;if(vr(e)>0)return!0;return!1}(e)}(r);o!==r._backpressure&&fr(r,!0)}function pr(e,t){return p(e._transformAlgorithm(t),void 0,(t=>{throw cr(e._controlledTransformStream,t),t}))}function mr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function yr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}function gr(e){return!e._readableCloseRequested&&"readable"===e._readableState}function wr(e){e._readableState="closed",e._readableCloseRequested=!0,e._readableController.close()}function Sr(e,t){"readable"===e._readableState&&(e._readableState="errored",e._readableStoredError=t),e._readableController.error(t)}function vr(e){return e._readableController.desiredSize}function Rr(e,t){"writable"!==e._writableState?qr(e):Tr(e,t)}function Tr(e,t){e._writableState="erroring",e._writableStoredError=t,!function(e){return e._writableHasInFlightOperation}(e)&&e._writableStarted&&qr(e)}function qr(e){e._writableState="errored"}function Cr(e){"erroring"===e._writableState&&qr(e)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),n(TransformStreamDefaultController.prototype.enqueue,"enqueue"),n(TransformStreamDefaultController.prototype.error,"error"),n(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof e.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,e.toStringTag,{value:"TransformStreamDefaultController",configurable:!0}); - -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js -var isFunction = __nccwpck_require__(5122); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/blobHelpers.js -/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ - -const CHUNK_SIZE = 65536; -async function* clonePart(part) { - const end = part.byteOffset + part.byteLength; - let position = part.byteOffset; - while (position !== end) { - const size = Math.min(end - position, CHUNK_SIZE); - const chunk = part.buffer.slice(position, position + size); - position += chunk.byteLength; - yield new Uint8Array(chunk); - } -} -async function* consumeNodeBlob(blob) { - let position = 0; - while (position !== blob.size) { - const chunk = blob.slice(position, Math.min(blob.size, position + CHUNK_SIZE)); - const buffer = await chunk.arrayBuffer(); - position += buffer.byteLength; - yield new Uint8Array(buffer); - } -} -async function* consumeBlobParts(parts, clone = false) { - for (const part of parts) { - if (ArrayBuffer.isView(part)) { - if (clone) { - yield* clonePart(part); - } - else { - yield part; - } - } - else if ((0,isFunction/* isFunction */.T)(part.stream)) { - yield* part.stream(); - } - else { - yield* consumeNodeBlob(part); - } - } -} -function* sliceBlob(blobParts, blobSize, start = 0, end) { - end !== null && end !== void 0 ? end : (end = blobSize); - let relativeStart = start < 0 - ? Math.max(blobSize + start, 0) - : Math.min(start, blobSize); - let relativeEnd = end < 0 - ? Math.max(blobSize + end, 0) - : Math.min(end, blobSize); - const span = Math.max(relativeEnd - relativeStart, 0); - let added = 0; - for (const part of blobParts) { - if (added >= span) { - break; - } - const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size; - if (relativeStart && partSize <= relativeStart) { - relativeStart -= partSize; - relativeEnd -= partSize; - } - else { - let chunk; - if (ArrayBuffer.isView(part)) { - chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd)); - added += chunk.byteLength; - } - else { - chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd)); - added += chunk.size; - } - relativeEnd -= partSize; - relativeStart = 0; - yield chunk; - } - } -} - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/Blob.js -/*! Based on fetch-blob. MIT License. Jimmy Wärting & David Frank */ -var __classPrivateFieldGet = (undefined && undefined.__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 = (undefined && undefined.__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 _Blob_parts, _Blob_type, _Blob_size; - - - -class Blob { - constructor(blobParts = [], options = {}) { - _Blob_parts.set(this, []); - _Blob_type.set(this, ""); - _Blob_size.set(this, 0); - options !== null && options !== void 0 ? options : (options = {}); - if (typeof blobParts !== "object" || blobParts === null) { - throw new TypeError("Failed to construct 'Blob': " - + "The provided value cannot be converted to a sequence."); - } - if (!(0,isFunction/* isFunction */.T)(blobParts[Symbol.iterator])) { - throw new TypeError("Failed to construct 'Blob': " - + "The object must have a callable @@iterator property."); - } - if (typeof options !== "object" && !(0,isFunction/* isFunction */.T)(options)) { - throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); - } - const encoder = new TextEncoder(); - for (const raw of blobParts) { - let part; - if (ArrayBuffer.isView(raw)) { - part = new Uint8Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength)); - } - else if (raw instanceof ArrayBuffer) { - part = new Uint8Array(raw.slice(0)); - } - else if (raw instanceof Blob) { - part = raw; - } - else { - part = encoder.encode(String(raw)); - } - __classPrivateFieldSet(this, _Blob_size, __classPrivateFieldGet(this, _Blob_size, "f") + (ArrayBuffer.isView(part) ? part.byteLength : part.size), "f"); - __classPrivateFieldGet(this, _Blob_parts, "f").push(part); - } - const type = options.type === undefined ? "" : String(options.type); - __classPrivateFieldSet(this, _Blob_type, /^[\x20-\x7E]*$/.test(type) ? type : "", "f"); - } - static [(_Blob_parts = new WeakMap(), _Blob_type = new WeakMap(), _Blob_size = new WeakMap(), Symbol.hasInstance)](value) { - return Boolean(value - && typeof value === "object" - && (0,isFunction/* isFunction */.T)(value.constructor) - && ((0,isFunction/* isFunction */.T)(value.stream) - || (0,isFunction/* isFunction */.T)(value.arrayBuffer)) - && /^(Blob|File)$/.test(value[Symbol.toStringTag])); - } - get type() { - return __classPrivateFieldGet(this, _Blob_type, "f"); - } - get size() { - return __classPrivateFieldGet(this, _Blob_size, "f"); - } - slice(start, end, contentType) { - return new Blob(sliceBlob(__classPrivateFieldGet(this, _Blob_parts, "f"), this.size, start, end), { - type: contentType - }); - } - async text() { - const decoder = new TextDecoder(); - let result = ""; - for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { - result += decoder.decode(chunk, { stream: true }); - } - result += decoder.decode(); - return result; - } - async arrayBuffer() { - const view = new Uint8Array(this.size); - let offset = 0; - for await (const chunk of consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"))) { - view.set(chunk, offset); - offset += chunk.length; - } - return view.buffer; - } - stream() { - const iterator = consumeBlobParts(__classPrivateFieldGet(this, _Blob_parts, "f"), true); - return new ReadableStream({ - async pull(controller) { - const { value, done } = await iterator.next(); - if (done) { - return queueMicrotask(() => controller.close()); - } - controller.enqueue(value); - }, - async cancel() { - await iterator.return(); - } - }); - } - get [Symbol.toStringTag]() { - return "Blob"; - } -} -Object.defineProperties(Blob.prototype, { - type: { enumerable: true }, - size: { enumerable: true }, - slice: { enumerable: true }, - stream: { enumerable: true }, - text: { enumerable: true }, - arrayBuffer: { enumerable: true } -}); - - -/***/ }), - -/***/ 2928: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ Z: () => (/* binding */ File) -/* harmony export */ }); -/* harmony import */ var _Blob_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(6220); -var __classPrivateFieldSet = (undefined && undefined.__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 = (undefined && undefined.__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 _File_name, _File_lastModified; - -class File extends _Blob_js__WEBPACK_IMPORTED_MODULE_0__/* .Blob */ .Y { - constructor(fileBits, name, options = {}) { - super(fileBits, options); - _File_name.set(this, void 0); - _File_lastModified.set(this, 0); - if (arguments.length < 2) { - throw new TypeError("Failed to construct 'File': 2 arguments required, " - + `but only ${arguments.length} present.`); - } - __classPrivateFieldSet(this, _File_name, String(name), "f"); - const lastModified = options.lastModified === undefined - ? Date.now() - : Number(options.lastModified); - if (!Number.isNaN(lastModified)) { - __classPrivateFieldSet(this, _File_lastModified, lastModified, "f"); - } - } - static [(_File_name = new WeakMap(), _File_lastModified = new WeakMap(), Symbol.hasInstance)](value) { - return value instanceof _Blob_js__WEBPACK_IMPORTED_MODULE_0__/* .Blob */ .Y - && value[Symbol.toStringTag] === "File" - && typeof value.name === "string"; - } - get name() { - return __classPrivateFieldGet(this, _File_name, "f"); - } - get lastModified() { - return __classPrivateFieldGet(this, _File_lastModified, "f"); - } - get webkitRelativePath() { - return ""; - } - get [Symbol.toStringTag]() { - return "File"; - } -} - - -/***/ }), - -/***/ 928: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ f: () => (/* binding */ isFile) -/* harmony export */ }); -/* harmony import */ var _File_js__WEBPACK_IMPORTED_MODULE_0__ = __nccwpck_require__(2928); - -const isFile = (value) => value instanceof _File_js__WEBPACK_IMPORTED_MODULE_0__/* .File */ .Z; - - -/***/ }), - -/***/ 5122: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => { - -/* harmony export */ __nccwpck_require__.d(__webpack_exports__, { -/* harmony export */ T: () => (/* binding */ isFunction) -/* harmony export */ }); -const isFunction = (value) => (typeof value === "function"); - - -/***/ }), - -/***/ 2472: -/***/ ((module) => { - -module.exports = /*#__PURE__*/JSON.parse('[[[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"]]'); - /***/ }) /******/ }); @@ -68155,9 +62166,6 @@ module.exports = /*#__PURE__*/JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45 /******/ return module.exports; /******/ } /******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __nccwpck_require__.m = __webpack_modules__; -/******/ /************************************************************************/ /******/ /* webpack/runtime/create fake namespace object */ /******/ (() => { @@ -68201,28 +62209,6 @@ module.exports = /*#__PURE__*/JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45 /******/ }; /******/ })(); /******/ -/******/ /* webpack/runtime/ensure chunk */ -/******/ (() => { -/******/ __nccwpck_require__.f = {}; -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __nccwpck_require__.e = (chunkId) => { -/******/ return Promise.all(Object.keys(__nccwpck_require__.f).reduce((promises, key) => { -/******/ __nccwpck_require__.f[key](chunkId, promises); -/******/ return promises; -/******/ }, [])); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/get javascript chunk filename */ -/******/ (() => { -/******/ // This function allow to reference async chunks -/******/ __nccwpck_require__.u = (chunkId) => { -/******/ // return url for filenames based on template -/******/ return "" + chunkId + ".index.js"; -/******/ }; -/******/ })(); -/******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) @@ -68252,69 +62238,6 @@ module.exports = /*#__PURE__*/JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45 /******/ /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; /******/ -/******/ /* webpack/runtime/import chunk loading */ -/******/ (() => { -/******/ // no baseURI -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // [resolve, Promise] = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 792: 0 -/******/ }; -/******/ -/******/ var installChunk = (data) => { -/******/ var {ids, modules, runtime} = data; -/******/ // add "modules" to the modules object, -/******/ // then flag all "ids" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0; -/******/ for(moduleId in modules) { -/******/ if(__nccwpck_require__.o(modules, moduleId)) { -/******/ __nccwpck_require__.m[moduleId] = modules[moduleId]; -/******/ } -/******/ } -/******/ if(runtime) runtime(__nccwpck_require__); -/******/ for(;i < ids.length; i++) { -/******/ chunkId = ids[i]; -/******/ if(__nccwpck_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ installedChunks[chunkId][0](); -/******/ } -/******/ installedChunks[ids[i]] = 0; -/******/ } -/******/ -/******/ } -/******/ -/******/ __nccwpck_require__.f.j = (chunkId, promises) => { -/******/ // import() chunk loading for javascript -/******/ var installedChunkData = __nccwpck_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined; -/******/ if(installedChunkData !== 0) { // 0 means "already installed". -/******/ -/******/ // a Promise means "currently loading". -/******/ if(installedChunkData) { -/******/ promises.push(installedChunkData[1]); -/******/ } else { -/******/ if(true) { // all chunks have JS -/******/ // setup Promise in chunk cache -/******/ var promise = import("./" + __nccwpck_require__.u(chunkId)).then(installChunk, (e) => { -/******/ if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined; -/******/ throw e; -/******/ }); -/******/ var promise = Promise.race([promise, new Promise((resolve) => (installedChunkData = installedChunks[chunkId] = [resolve]))]) -/******/ promises.push(installedChunkData[1] = promise); -/******/ } -/******/ } -/******/ } -/******/ }; -/******/ -/******/ // no prefetching -/******/ -/******/ // no preloaded -/******/ -/******/ // no external install chunk -/******/ -/******/ // no on chunks loaded -/******/ })(); -/******/ /************************************************************************/ var __webpack_exports__ = {}; @@ -68337,2326 +62260,401 @@ __nccwpck_require__.d(src_core_namespaceObject, { var lib_core = __nccwpck_require__(7484); // EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js var github = __nccwpck_require__(3228); -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs -const default_format = 'RFC3986'; -const formatters = { - RFC1738: (v) => String(v).replace(/%20/g, '+'), - RFC3986: (v) => String(v), -}; -const RFC1738 = 'RFC1738'; -const RFC3986 = 'RFC3986'; -//# sourceMappingURL=formats.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs +;// CONCATENATED MODULE: ./node_modules/openai/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} -const has = Object.prototype.hasOwnProperty; -const is_array = Array.isArray; -const hex_table = (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/uuid.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * https://stackoverflow.com/a/2117523 + */ +let uuid4 = function () { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); } - return array; -})(); -function compact_queue(queue) { - while (queue.length > 1) { - const item = queue.pop(); - if (!item) - continue; - const obj = item.obj[item.prop]; - if (is_array(obj)) { - const compacted = []; - for (let j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); +}; +//# sourceMappingURL=uuid.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/errors.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); +} +const castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === 'object' && err !== null) { + try { + if (Object.prototype.toString.call(err) === '[object Error]') { + // @ts-ignore - not all envs have native support for cause yet + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + // @ts-ignore - not all envs have native support for cause yet + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; } - // @ts-ignore - item.obj[item.prop] = compacted; } - } -} -function array_to_object(source, options) { - const obj = options && options.plainObjects ? Object.create(null) : {}; - for (let i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; + catch { } + try { + return new Error(JSON.stringify(err)); } + catch { } } - return obj; + return new Error(err); +}; +//# sourceMappingURL=errors.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/error.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class error_OpenAIError extends Error { } -function merge(target, source, options = {}) { - if (!source) { - return target; +class APIError extends error_OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('x-request-id'); + this.error = error; + const data = error; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; } - if (typeof source !== 'object') { - if (is_array(target)) { - target.push(source); + 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}`; } - else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || - !has.call(Object.prototype, source)) { - target[source] = true; - } + if (status) { + return `${status} status code (no body)`; } - else { - return [target, source]; + if (msg) { + return msg; } - return target; - } - if (!target || typeof target !== 'object') { - return [target].concat(source); - } - let mergeTarget = target; - if (is_array(target) && !is_array(source)) { - // @ts-ignore - mergeTarget = array_to_object(target, options); - } - if (is_array(target) && is_array(source)) { - source.forEach(function (item, i) { - if (has.call(target, i)) { - const targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = merge(targetItem, item, options); - } - else { - target.push(item); - } - } - else { - target[i] = item; - } - }); - return target; + return '(no status code or body)'; } - return Object.keys(source).reduce(function (acc, key) { - const value = source[key]; - if (has.call(acc, key)) { - acc[key] = merge(acc[key], value, options); + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); } - else { - acc[key] = value; + const error = errorResponse?.['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); } - return acc; - }, mergeTarget); -} -function assign_single_source(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -} -function decode(str, _, charset) { - const strWithoutPlus = str.replace(/\+/g, ' '); - if (charset === 'iso-8859-1') { - // unescape never throws, no try...catch needed: - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - // utf-8 - try { - return decodeURIComponent(strWithoutPlus); - } - catch (e) { - return strWithoutPlus; + 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); } } -const limit = 1024; -const encode = (str, _defaultEncoder, charset, _kind, format) => { - // This code was originally written by Brian White for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); } - let string = str; - if (typeof str === 'symbol') { - string = Symbol.prototype.toString.call(str); +} +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; } - else if (typeof str !== 'string') { - string = String(str); +} +class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); } - if (charset === 'iso-8859-1') { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { - return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; - }); +} +class BadRequestError extends APIError { +} +class AuthenticationError extends APIError { +} +class PermissionDeniedError extends APIError { +} +class NotFoundError extends APIError { +} +class ConflictError extends APIError { +} +class UnprocessableEntityError extends APIError { +} +class RateLimitError extends APIError { +} +class InternalServerError extends APIError { +} +class LengthFinishReasonError extends error_OpenAIError { + constructor() { + super(`Could not parse response content as the length limit was reached`); } - let out = ''; - for (let j = 0; j < string.length; j += limit) { - const segment = string.length >= limit ? string.slice(j, j + limit) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 0x2d || // - - c === 0x2e || // . - c === 0x5f || // _ - c === 0x7e || // ~ - (c >= 0x30 && c <= 0x39) || // 0-9 - (c >= 0x41 && c <= 0x5a) || // a-z - (c >= 0x61 && c <= 0x7a) || // A-Z - (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) - ) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 0x80) { - arr[arr.length] = hex_table[c]; - continue; - } - if (c < 0x800) { - arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - if (c < 0xd800 || c >= 0xe000) { - arr[arr.length] = - hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - i += 1; - c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); - arr[arr.length] = - hex_table[0xf0 | (c >> 18)] + - hex_table[0x80 | ((c >> 12) & 0x3f)] + - hex_table[0x80 | ((c >> 6) & 0x3f)] + - hex_table[0x80 | (c & 0x3f)]; - } - out += arr.join(''); +} +class ContentFilterFinishReasonError extends error_OpenAIError { + constructor() { + super(`Could not parse response content as the request was rejected by the content filter`); } - return out; +} +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/values.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); }; -function compact(value) { - const queue = [{ obj: { o: value }, prop: 'o' }]; - const refs = []; - for (let i = 0; i < queue.length; ++i) { - const item = queue[i]; - // @ts-ignore - const obj = item.obj[item.prop]; - const keys = Object.keys(obj); - for (let j = 0; j < keys.length; ++j) { - const key = keys[j]; - const val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } - } +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function maybeObj(x) { + if (typeof x !== 'object') { + return {}; } - compact_queue(queue); - return value; -} -function is_regexp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; + return x ?? {}; } -function is_buffer(obj) { - if (!obj || typeof obj !== 'object') { +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + return true; } -function combine(a, b) { - return [].concat(a, b); +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); } -function maybe_map(val, fn) { - if (is_array(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; - } - return fn(val); -} -//# sourceMappingURL=utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs - - -const stringify_has = Object.prototype.hasOwnProperty; -const array_prefix_generators = { - brackets(prefix) { - return String(prefix) + '[]'; - }, - comma: 'comma', - indices(prefix, key) { - return String(prefix) + '[' + key + ']'; - }, - repeat(prefix) { - return String(prefix); - }, -}; -const stringify_is_array = Array.isArray; -const push = Array.prototype.push; -const push_to_array = function (arr, value_or_array) { - push.apply(arr, stringify_is_array(value_or_array) ? value_or_array : [value_or_array]); -}; -const to_ISO = Date.prototype.toISOString; -const defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: 'indices', - charset: 'utf-8', - charsetSentinel: false, - delimiter: '&', - encode: true, - encodeDotInKeys: false, - encoder: encode, - encodeValuesOnly: false, - format: default_format, - formatter: formatters[default_format], - /** @deprecated */ - indices: false, - serializeDate(date) { - return to_ISO.call(date); - }, - skipNulls: false, - strictNullHandling: false, -}; -function is_non_nullish_primitive(v) { - return (typeof v === 'string' || - typeof v === 'number' || - typeof v === 'boolean' || - typeof v === 'symbol' || - typeof v === 'bigint'); -} -const sentinel = {}; -function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { - // Where object last appeared in the ref tree - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== 'undefined') { - if (pos === step) { - throw new RangeError('Cyclic object value'); - } - else { - find_flag = true; // Break while - } - } - if (typeof tmp_sc.get(sentinel) === 'undefined') { - step = 0; - } - } - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } - else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } - else if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { - obj = maybe_map(obj, function (value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? - // @ts-expect-error - encoder(prefix, defaults.encoder, charset, 'key', format) - : prefix; - } - obj = ''; - } - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix - // @ts-expect-error - : encoder(prefix, defaults.encoder, charset, 'key', format); - return [ - formatter?.(key_value) + - '=' + - // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), - ]; - } - return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === 'undefined') { - return values; - } - let obj_keys; - if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { - // we need to join elements in - if (encodeValuesOnly && encoder) { - // @ts-expect-error values only - obj = maybe_map(obj, encoder); - } - obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; - } - else if (stringify_is_array(filter)) { - obj_keys = filter; - } - else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); - const adjusted_prefix = commaRoundTrip && stringify_is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; - if (allowEmptyArrays && stringify_is_array(obj) && obj.length === 0) { - return adjusted_prefix + '[]'; - } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = - // @ts-ignore - typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; - if (skipNulls && value === null) { - continue; - } - // @ts-ignore - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; - const key_prefix = stringify_is_array(obj) ? - typeof generateArrayPrefix === 'function' ? - generateArrayPrefix(adjusted_prefix, encoded_key) - : adjusted_prefix - : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); - sideChannel.set(object, step); - const valueSideChannel = new WeakMap(); - valueSideChannel.set(sentinel, sideChannel); - push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === 'comma' && encodeValuesOnly && stringify_is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); - } - return values; -} -function normalize_stringify_options(opts = defaults) { - if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { - throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); - } - if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { - throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); - } - if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); - } - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); - } - let format = default_format; - if (typeof opts.format !== 'undefined') { - if (!stringify_has.call(formatters, opts.format)) { - throw new TypeError('Unknown format option provided.'); - } - format = opts.format; - } - const formatter = formatters[format]; - let filter = defaults.filter; - if (typeof opts.filter === 'function' || stringify_is_array(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } - else if ('indices' in opts) { - arrayFormat = opts.indices ? 'indices' : 'repeat'; - } - else { - arrayFormat = defaults.arrayFormat; - } - if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { - throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); - } - const allowDots = typeof opts.allowDots === 'undefined' ? - !!opts.encodeDotInKeys === true ? - true - : defaults.allowDots - : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots: allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat: arrayFormat, - charset: charset, - charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter: filter, - format: format, - formatter: formatter, - serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === 'function' ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, - }; -} -function stringify(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - let obj_keys; - let filter; - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } - else if (stringify_is_array(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== 'object' || obj === null) { - return ''; - } - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array(keys, inner_stringify(obj[key], key, - // @ts-expect-error - generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? '?' : ''; - if (options.charsetSentinel) { - if (options.charset === 'iso-8859-1') { - // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark - prefix += 'utf8=%26%2310003%3B&'; - } - else { - // encodeURIComponent('✓') - prefix += 'utf8=%E2%9C%93&'; - } - } - return joined.length > 0 ? prefix + joined : ''; -} -//# sourceMappingURL=stringify.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/version.mjs -const VERSION = '4.98.0'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_shims/registry.mjs -let auto = false; -let kind = undefined; -let registry_fetch = undefined; -let index_Request = (/* unused pure expression or super */ null && (undefined)); -let registry_Response = (/* unused pure expression or super */ null && (undefined)); -let registry_Headers = (/* unused pure expression or super */ null && (undefined)); -let registry_FormData = undefined; -let registry_Blob = (/* unused pure expression or super */ null && (undefined)); -let registry_File = undefined; -let registry_ReadableStream = undefined; -let registry_getMultipartRequestOptions = undefined; -let getDefaultAgent = undefined; -let fileFromPath = undefined; -let isFsReadStream = undefined; -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; - registry_fetch = shims.fetch; - index_Request = shims.Request; - registry_Response = shims.Response; - registry_Headers = shims.Headers; - registry_FormData = shims.FormData; - registry_Blob = shims.Blob; - registry_File = shims.File; - registry_ReadableStream = shims.ReadableStream; - registry_getMultipartRequestOptions = shims.getMultipartRequestOptions; - getDefaultAgent = shims.getDefaultAgent; - fileFromPath = shims.fileFromPath; - isFsReadStream = shims.isFsReadStream; -} -//# sourceMappingURL=registry.mjs.map -// EXTERNAL MODULE: ./node_modules/node-fetch/lib/index.js -var lib = __nccwpck_require__(6705); -// EXTERNAL MODULE: external "util" -var external_util_ = __nccwpck_require__(9023); -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/File.js -var esm_File = __nccwpck_require__(2928); -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/isFile.js -var isFile = __nccwpck_require__(928); -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/Blob.js + 2 modules -var esm_Blob = __nccwpck_require__(6220); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/isBlob.js - -const isBlob = (value) => value instanceof esm_Blob/* Blob */.Y; - -// EXTERNAL MODULE: ./node_modules/formdata-node/lib/esm/isFunction.js -var isFunction = __nccwpck_require__(5122); -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/deprecateConstructorEntries.js - -const deprecateConstructorEntries = (0,external_util_.deprecate)(() => { }, "Constructor \"entries\" argument is not spec-compliant " - + "and will be removed in next major release."); - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/FormData.js -var __classPrivateFieldGet = (undefined && undefined.__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 _FormData_instances, _FormData_entries, _FormData_setEntry; - - - - - - -class FormData_FormData { - constructor(entries) { - _FormData_instances.add(this); - _FormData_entries.set(this, new Map()); - if (entries) { - deprecateConstructorEntries(); - entries.forEach(({ name, value, fileName }) => this.append(name, value, fileName)); - } - } - static [(_FormData_entries = new WeakMap(), _FormData_instances = new WeakSet(), Symbol.hasInstance)](value) { - return Boolean(value - && (0,isFunction/* isFunction */.T)(value.constructor) - && value[Symbol.toStringTag] === "FormData" - && (0,isFunction/* isFunction */.T)(value.append) - && (0,isFunction/* isFunction */.T)(value.set) - && (0,isFunction/* isFunction */.T)(value.get) - && (0,isFunction/* isFunction */.T)(value.getAll) - && (0,isFunction/* isFunction */.T)(value.has) - && (0,isFunction/* isFunction */.T)(value.delete) - && (0,isFunction/* isFunction */.T)(value.entries) - && (0,isFunction/* isFunction */.T)(value.values) - && (0,isFunction/* isFunction */.T)(value.keys) - && (0,isFunction/* isFunction */.T)(value[Symbol.iterator]) - && (0,isFunction/* isFunction */.T)(value.forEach)); - } - append(name, value, fileName) { - __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { - name, - fileName, - append: true, - rawValue: value, - argsLength: arguments.length - }); - } - set(name, value, fileName) { - __classPrivateFieldGet(this, _FormData_instances, "m", _FormData_setEntry).call(this, { - name, - fileName, - append: false, - rawValue: value, - argsLength: arguments.length - }); - } - get(name) { - const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); - if (!field) { - return null; - } - return field[0]; - } - getAll(name) { - const field = __classPrivateFieldGet(this, _FormData_entries, "f").get(String(name)); - if (!field) { - return []; - } - return field.slice(); - } - has(name) { - return __classPrivateFieldGet(this, _FormData_entries, "f").has(String(name)); - } - delete(name) { - __classPrivateFieldGet(this, _FormData_entries, "f").delete(String(name)); - } - *keys() { - for (const key of __classPrivateFieldGet(this, _FormData_entries, "f").keys()) { - yield key; - } - } - *entries() { - for (const name of this.keys()) { - const values = this.getAll(name); - for (const value of values) { - yield [name, value]; - } - } - } - *values() { - for (const [, value] of this) { - yield value; - } - } - [(_FormData_setEntry = function _FormData_setEntry({ name, rawValue, append, fileName, argsLength }) { - const methodName = append ? "append" : "set"; - if (argsLength < 2) { - throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` - + `2 arguments required, but only ${argsLength} present.`); - } - name = String(name); - let value; - if ((0,isFile/* isFile */.f)(rawValue)) { - value = fileName === undefined - ? rawValue - : new esm_File/* File */.Z([rawValue], fileName, { - type: rawValue.type, - lastModified: rawValue.lastModified - }); - } - else if (isBlob(rawValue)) { - value = new esm_File/* File */.Z([rawValue], fileName === undefined ? "blob" : fileName, { - type: rawValue.type - }); - } - else if (fileName) { - throw new TypeError(`Failed to execute '${methodName}' on 'FormData': ` - + "parameter 2 is not of type 'Blob'."); - } - else { - value = String(rawValue); - } - const values = __classPrivateFieldGet(this, _FormData_entries, "f").get(name); - if (!values) { - return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); - } - if (!append) { - return void __classPrivateFieldGet(this, _FormData_entries, "f").set(name, [value]); - } - values.push(value); - }, Symbol.iterator)]() { - return this.entries(); - } - forEach(callback, thisArg) { - for (const [name, value] of this) { - callback.call(thisArg, value, name, this); - } - } - get [Symbol.toStringTag]() { - return "FormData"; - } - [external_util_.inspect.custom]() { - return this[Symbol.toStringTag]; - } -} - -;// CONCATENATED MODULE: ./node_modules/formdata-node/lib/esm/index.js - - - - -// EXTERNAL MODULE: ./node_modules/agentkeepalive/index.js -var agentkeepalive = __nccwpck_require__(3873); -// EXTERNAL MODULE: ./node_modules/abort-controller/dist/abort-controller.js -var abort_controller = __nccwpck_require__(7413); -;// CONCATENATED MODULE: external "node:fs" -const external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs"); -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/createBoundary.js -const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; -function createBoundary() { - let size = 16; - let res = ""; - while (size--) { - res += alphabet[(Math.random() * alphabet.length) << 0]; - } - return res; -} -/* harmony default export */ const util_createBoundary = (createBoundary); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isPlainObject.js -const getType = (value) => (Object.prototype.toString.call(value).slice(8, -1).toLowerCase()); -function isPlainObject(value) { - if (getType(value) !== "object") { - return false; - } - const pp = Object.getPrototypeOf(value); - if (pp === null || pp === undefined) { - return true; - } - const Ctor = pp.constructor && pp.constructor.toString(); - return Ctor === Object.toString(); -} -/* harmony default export */ const util_isPlainObject = (isPlainObject); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/normalizeValue.js -const normalizeValue = (value) => String(value) - .replace(/\r|\n/g, (match, i, str) => { - if ((match === "\r" && str[i + 1] !== "\n") - || (match === "\n" && str[i - 1] !== "\r")) { - return "\r\n"; - } - return match; -}); -/* harmony default export */ const util_normalizeValue = (normalizeValue); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/escapeName.js -const escapeName = (name) => String(name) - .replace(/\r/g, "%0D") - .replace(/\n/g, "%0A") - .replace(/"/g, "%22"); -/* harmony default export */ const util_escapeName = (escapeName); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFunction.js -const isFunction_isFunction = (value) => (typeof value === "function"); -/* harmony default export */ const util_isFunction = (isFunction_isFunction); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFileLike.js - -const isFileLike = (value) => Boolean(value - && typeof value === "object" - && util_isFunction(value.constructor) - && value[Symbol.toStringTag] === "File" - && util_isFunction(value.stream) - && value.name != null - && value.size != null - && value.lastModified != null); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/util/isFormData.js - -const isFormData = (value) => Boolean(value - && util_isFunction(value.constructor) - && value[Symbol.toStringTag] === "FormData" - && util_isFunction(value.append) - && util_isFunction(value.getAll) - && util_isFunction(value.entries) - && util_isFunction(value[Symbol.iterator])); -const isFormDataLike = (/* unused pure expression or super */ null && (isFormData)); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/FormDataEncoder.js -var __classPrivateFieldSet = (undefined && undefined.__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 FormDataEncoder_classPrivateFieldGet = (undefined && undefined.__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 _FormDataEncoder_instances, _FormDataEncoder_CRLF, _FormDataEncoder_CRLF_BYTES, _FormDataEncoder_CRLF_BYTES_LENGTH, _FormDataEncoder_DASHES, _FormDataEncoder_encoder, _FormDataEncoder_footer, _FormDataEncoder_form, _FormDataEncoder_options, _FormDataEncoder_getFieldHeader; - - - - - - -const defaultOptions = { - enableAdditionalHeaders: false -}; -class FormDataEncoder { - constructor(form, boundaryOrOptions, options) { - _FormDataEncoder_instances.add(this); - _FormDataEncoder_CRLF.set(this, "\r\n"); - _FormDataEncoder_CRLF_BYTES.set(this, void 0); - _FormDataEncoder_CRLF_BYTES_LENGTH.set(this, void 0); - _FormDataEncoder_DASHES.set(this, "-".repeat(2)); - _FormDataEncoder_encoder.set(this, new TextEncoder()); - _FormDataEncoder_footer.set(this, void 0); - _FormDataEncoder_form.set(this, void 0); - _FormDataEncoder_options.set(this, void 0); - if (!isFormData(form)) { - throw new TypeError("Expected first argument to be a FormData instance."); - } - let boundary; - if (util_isPlainObject(boundaryOrOptions)) { - options = boundaryOrOptions; - } - else { - boundary = boundaryOrOptions; - } - if (!boundary) { - boundary = util_createBoundary(); - } - if (typeof boundary !== "string") { - throw new TypeError("Expected boundary argument to be a string."); - } - if (options && !util_isPlainObject(options)) { - throw new TypeError("Expected options argument to be an object."); - } - __classPrivateFieldSet(this, _FormDataEncoder_form, form, "f"); - __classPrivateFieldSet(this, _FormDataEncoder_options, { ...defaultOptions, ...options }, "f"); - __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")), "f"); - __classPrivateFieldSet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f").byteLength, "f"); - this.boundary = `form-data-boundary-${boundary}`; - this.contentType = `multipart/form-data; boundary=${this.boundary}`; - __classPrivateFieldSet(this, _FormDataEncoder_footer, FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`), "f"); - this.contentLength = String(this.getContentLength()); - this.headers = Object.freeze({ - "Content-Type": this.contentType, - "Content-Length": this.contentLength - }); - Object.defineProperties(this, { - boundary: { writable: false, configurable: false }, - contentType: { writable: false, configurable: false }, - contentLength: { writable: false, configurable: false }, - headers: { writable: false, configurable: false } - }); - } - getContentLength() { - let length = 0; - for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f")) { - const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); - length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value).byteLength; - length += isFileLike(value) ? value.size : value.byteLength; - length += FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES_LENGTH, "f"); - } - return length + FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f").byteLength; - } - *values() { - for (const [name, raw] of FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_form, "f").entries()) { - const value = isFileLike(raw) ? raw : FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(util_normalizeValue(raw)); - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_instances, "m", _FormDataEncoder_getFieldHeader).call(this, name, value); - yield value; - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF_BYTES, "f"); - } - yield FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_footer, "f"); - } - async *encode() { - for (const part of this.values()) { - if (isFileLike(part)) { - yield* part.stream(); - } - else { - yield part; - } - } - } - [(_FormDataEncoder_CRLF = new WeakMap(), _FormDataEncoder_CRLF_BYTES = new WeakMap(), _FormDataEncoder_CRLF_BYTES_LENGTH = new WeakMap(), _FormDataEncoder_DASHES = new WeakMap(), _FormDataEncoder_encoder = new WeakMap(), _FormDataEncoder_footer = new WeakMap(), _FormDataEncoder_form = new WeakMap(), _FormDataEncoder_options = new WeakMap(), _FormDataEncoder_instances = new WeakSet(), _FormDataEncoder_getFieldHeader = function _FormDataEncoder_getFieldHeader(name, value) { - let header = ""; - header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_DASHES, "f")}${this.boundary}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; - header += `Content-Disposition: form-data; name="${util_escapeName(name)}"`; - if (isFileLike(value)) { - header += `; filename="${util_escapeName(value.name)}"${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}`; - header += `Content-Type: ${value.type || "application/octet-stream"}`; - } - if (FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_options, "f").enableAdditionalHeaders === true) { - header += `${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f")}Content-Length: ${isFileLike(value) ? value.size : value.byteLength}`; - } - return FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_encoder, "f").encode(`${header}${FormDataEncoder_classPrivateFieldGet(this, _FormDataEncoder_CRLF, "f").repeat(2)}`); - }, Symbol.iterator)]() { - return this.values(); - } - [Symbol.asyncIterator]() { - return this.encode(); - } -} -const Encoder = (/* unused pure expression or super */ null && (FormDataEncoder)); - -;// CONCATENATED MODULE: ./node_modules/form-data-encoder/lib/esm/index.js - - - - - - -// EXTERNAL MODULE: external "node:stream" -var external_node_stream_ = __nccwpck_require__(7075); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/MultipartBody.mjs -/** - * 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'; - } -} -//# sourceMappingURL=MultipartBody.mjs.map -;// CONCATENATED MODULE: external "node:stream/web" -const web_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream/web"); -;// CONCATENATED MODULE: ./node_modules/openai/_shims/node-runtime.mjs - - - - - - - - - -let fileFromPathWarned = false; -async function node_runtime_fileFromPath(path, ...args) { - // this import fails in environments that don't handle export maps correctly, like old versions of Jest - const { fileFromPath: _fileFromPath } = await __nccwpck_require__.e(/* import() */ 33).then(__nccwpck_require__.bind(__nccwpck_require__, 2033)); - 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({ keepAlive: true, timeout: 5 * 60 * 1000 }); -const defaultHttpsAgent = new agentkeepalive.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); -async function node_runtime_getMultipartRequestOptions(form, opts) { - const encoder = new FormDataEncoder(form); - const readable = external_node_stream_.Readable.from(encoder); - const body = new 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.AbortController; - } - return { - kind: 'node', - fetch: lib, - Request: lib.Request, - Response: lib.Response, - Headers: lib.Headers, - FormData: FormData_FormData, - Blob: esm_Blob/* Blob */.Y, - File: esm_File/* File */.Z, - ReadableStream: web_namespaceObject.ReadableStream, - getMultipartRequestOptions: node_runtime_getMultipartRequestOptions, - getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), - fileFromPath: node_runtime_fileFromPath, - isFsReadStream: (value) => value instanceof external_node_fs_namespaceObject.ReadStream, - }; -} -//# sourceMappingURL=node-runtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_shims/index.mjs -/** - * Disclaimer: modules in _shims aren't intended to be imported by SDK users. - */ - - -const init = () => { - if (!kind) setShims(getRuntime(), { auto: true }); -}; - - -init(); - -;// CONCATENATED MODULE: ./node_modules/openai/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_OpenAIError extends Error { -} -class APIError extends error_OpenAIError { - constructor(status, error, message, headers) { - super(`${APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.request_id = headers?.['x-request-id']; - this.error = error; - const data = error; - this.code = data?.['code']; - this.param = data?.['param']; - this.type = data?.['type']; - } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError({ message, 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); - } -} -class APIUserAbortError extends APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); - } -} -class APIConnectionError extends APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; - } -} -class APIConnectionTimeoutError extends APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); - } -} -class BadRequestError extends APIError { -} -class AuthenticationError extends APIError { -} -class PermissionDeniedError extends APIError { -} -class NotFoundError extends APIError { -} -class ConflictError extends APIError { -} -class UnprocessableEntityError extends APIError { -} -class RateLimitError extends APIError { -} -class InternalServerError extends APIError { -} -class LengthFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the length limit was reached`); - } -} -class ContentFilterFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the request was rejected by the content filter`); - } -} -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/decoders/line.mjs -var line_classPrivateFieldSet = (undefined && undefined.__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 line_classPrivateFieldGet = (undefined && undefined.__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 _LineDecoder_carriageReturnIndex; - -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class LineDecoder { - constructor() { - _LineDecoder_carriageReturnIndex.set(this, void 0); - this.buffer = new Uint8Array(); - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - decode(chunk) { - if (chunk == null) { - return []; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? new TextEncoder().encode(chunk) - : chunk; - let newData = new Uint8Array(this.buffer.length + binaryChunk.length); - newData.set(this.buffer); - newData.set(binaryChunk, this.buffer.length); - this.buffer = newData; - const lines = []; - let patternIndex; - while ((patternIndex = findNewlineIndex(this.buffer, line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { - // skip until we either get a corresponding `\n`, a new `\r` or nothing - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; - } - // we got double \r or \rtext\n - if (line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(this.decodeText(this.buffer.slice(0, line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); - this.buffer = this.buffer.slice(line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")); - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - continue; - } - const endIndex = line_classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = this.decodeText(this.buffer.slice(0, endIndex)); - lines.push(line); - this.buffer = this.buffer.slice(patternIndex.index); - line_classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - return lines; - } - decodeText(bytes) { - if (bytes == null) - return ''; - if (typeof bytes === 'string') - return bytes; - // Node: - if (typeof Buffer !== 'undefined') { - if (bytes instanceof Buffer) { - return bytes.toString(); - } - if (bytes instanceof Uint8Array) { - return Buffer.from(bytes).toString(); - } - throw new error_OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); - } - // Browser - if (typeof TextDecoder !== 'undefined') { - if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { - this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8')); - return this.textDecoder.decode(bytes); - } - throw new error_OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); - } - throw new error_OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); - } - flush() { - if (!this.buffer.length) { - return []; - } - return this.decode('\n'); - } -} -_LineDecoder_carriageReturnIndex = new WeakMap(); -// prettier-ignore -LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); -LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; -/** - * This function searches the buffer for the end patterns, (\r or \n) - * and returns an object with the index preceding the matched newline and the - * index after the newline char. `null` is returned if no new line is found. - * - * ```ts - * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } - * ``` - */ -function findNewlineIndex(buffer, startIndex) { - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = startIndex ?? 0; i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; - } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; -} -function findDoubleNewlineIndex(buffer) { - // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) - // and returns the index right after the first occurrence of any pattern, - // or -1 if none of the patterns are found. - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - // \n\n - return i + 2; - } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - // \r\r - return i + 2; - } - if (buffer[i] === carriage && - buffer[i + 1] === newline && - i + 3 < buffer.length && - buffer[i + 2] === carriage && - buffer[i + 3] === newline) { - // \r\n\r\n - return i + 4; - } - } - return -1; -} -//# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/stream-utils.mjs -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; -} -//# sourceMappingURL=stream-utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs - - - - - - -class Stream { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; - } - static fromSSEResponse(response, controller) { - let consumed = false; - async function* iterator() { - if (consumed) { - throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of _iterSSEMessages(response, controller)) { - if (done) - continue; - if (sse.data.startsWith('[DONE]')) { - done = true; - continue; - } - if (sse.event === null || - sse.event.startsWith('response.') || - sse.event.startsWith('transcript.')) { - let data; - try { - data = JSON.parse(sse.data); - } - catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } - if (data && data.error) { - throw new APIError(undefined, data.error, undefined, createResponseHeaders(response.headers)); - } - yield data; - } - else { - let data; - try { - data = JSON.parse(sse.data); - } - catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } - // TODO: Is this where the error should be thrown? - if (sse.event == 'error') { - throw new APIError(undefined, data.error, data.message, undefined); - } - yield { event: sse.event, data: data }; - } - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (e instanceof Error && e.name === 'AbortError') - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new Stream(iterator, controller); - } - /** - * Generates a Stream from a newline-separated ReadableStream - * where each item is a JSON value. - */ - static fromReadableStream(readableStream, controller) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new LineDecoder(); - const iter = ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } - } - async function* iterator() { - if (consumed) { - throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (e instanceof Error && e.name === 'AbortError') - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new Stream(iterator, controller); - } - [Symbol.asyncIterator]() { - return this.iterator(); - } - /** - * Splits the stream into two streams which can be - * independently read from at different speeds. - */ - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue) => { - return { - next: () => { - if (queue.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue.shift(); - }, - }; - }; - return [ - new Stream(() => teeIterator(left), this.controller), - new Stream(() => teeIterator(right), this.controller), - ]; - } - /** - * Converts this stream to a newline-separated ReadableStream of - * JSON stringified values in the stream - * which can be turned back into a Stream with `Stream.fromReadableStream()`. - */ - toReadableStream() { - const self = this; - let iter; - const encoder = new TextEncoder(); - return new registry_ReadableStream({ - async start() { - iter = self[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = encoder.encode(JSON.stringify(value) + '\n'); - ctrl.enqueue(bytes); - } - catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - }, - }); - } -} -async function* _iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - throw new error_OpenAIError(`Attempted to iterate over a response with no body`); - } - const sseDecoder = new SSEDecoder(); - const lineDecoder = new LineDecoder(); - const iter = ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -/** - * Given an async iterable iterator, iterates over it and yields full - * SSE chunks, i.e. yields when a double new-line is encountered. - */ -async function* iterSSEChunks(iterator) { - let data = new Uint8Array(); - for await (const chunk of iterator) { - if (chunk == null) { - continue; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? new TextEncoder().encode(chunk) - : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); - } - } - if (data.length > 0) { - yield data; - } -} -class SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } +function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); } -function partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; +const ensurePresent = (value) => { + if (value == null) { + throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); } - return [str, '', '']; -} -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/uploads.mjs - - -const isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -const uploads_isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - isBlobLike(value); -/** - * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check - * adds the arrayBuffer() method type because it is available and used at runtime - */ -const isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -const isUploadable = (value) => { - return uploads_isFileLike(value) || isResponseLike(value) || isFsReadStream(value); + return value; }; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function toFile(value, name, options) { - // If it's a promise, resolve it. - value = await value; - // If we've been given a `File` we don't need to do anything - if (uploads_isFileLike(value)) { - return value; - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop() ?? 'unknown_file'); - // we need to convert the `Blob` into an array buffer because the `Blob` class - // that `node-fetch` defines is incompatible with the web standard which results - // in `new File` interpreting it as a string instead of binary data. - const data = isBlobLike(blob) ? [(await blob.arrayBuffer())] : [blob]; - return new registry_File(data, name, options); - } - const bits = await getBytes(value); - name || (name = getName(value) ?? 'unknown_file'); - if (!options?.type) { - const type = bits[0]?.type; - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return new registry_File(bits, name, options); -} -async function getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (isBlobLike(value)) { - parts.push(await value.arrayBuffer()); - } - else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(chunk); // TODO, consider validating? - } +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_OpenAIError(`${name} must be an integer`); } - else { - throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor - ?.name}; props: ${propsForError(value)}`); + if (n < 0) { + throw new error_OpenAIError(`${name} must be a positive integer`); } - return parts; -} -function propsForError(value) { - const props = Object.getOwnPropertyNames(value); - return `[${props.map((p) => `"${p}"`).join(', ')}]`; -} -function getName(value) { - return (getStringFromMaybeBuffer(value.name) || - getStringFromMaybeBuffer(value.filename) || - // For fs.ReadStream - getStringFromMaybeBuffer(value.path)?.split(/[\\/]/).pop()); -} -const getStringFromMaybeBuffer = (x) => { - if (typeof x === 'string') - return x; - if (typeof Buffer !== 'undefined' && x instanceof Buffer) - return String(x); - return undefined; + return n; }; -const isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const maybeMultipartFormRequestOptions = async (opts) => { - if (!hasUploadableValue(opts.body)) - return opts; - const form = await createForm(opts.body); - return getMultipartRequestOptions(form, opts); +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`); }; -const multipartFormRequestOptions = async (opts) => { - const form = await createForm(opts.body); - return registry_getMultipartRequestOptions(form, opts); +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`); }; -const createForm = async (body) => { - const form = new registry_FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); }; -const hasUploadableValue = (value) => { - if (isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (hasUploadableValue(value[k])) - return true; - } +const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; } - return false; + return coerceInteger(value); }; -const addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (isUploadable(value)) { - const file = await toFile(value); - form.append(key, file); +const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + return coerceFloat(value); +}; +const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + return coerceBoolean(value); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + catch (err) { + return undefined; } }; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core.mjs -var core_classPrivateFieldSet = (undefined && undefined.__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 core_classPrivateFieldGet = (undefined && undefined.__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; - - - - -// try running side effects outside of _shims/index to workaround https://github.com/vercel/next.js/issues/76881 -init(); - +//# sourceMappingURL=values.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/sleep.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//# sourceMappingURL=sleep.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -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'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - debug('response', response.status, response.url, response.headers, json); - return _addRequestID(json, response); - } - const text = await response.text(); - debug('response', response.status, response.url, response.headers, text); - // TODO handle blob, arraybuffer, other content types, etc. - return text; -} -function _addRequestID(value, response) { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return value; - } - return Object.defineProperty(value, '_request_id', { - value: response.headers.get('x-request-id'), - enumerable: false, - }); -} -/** - * 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) => _addRequestID(transform(await this.parseResponse(props), props), props.response)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` 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, the raw `Response` instance and the ID of the request, - * returned via the X-Request-ID header which is useful for debugging requests and reporting - * issues to OpenAI. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` 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, request_id: response.headers.get('x-request-id') }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then(this.parseResponse); - } - return this.parsedPromise; +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; } - catch(onrejected) { - return this.parse().catch(onrejected); + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; } - finally(onfinally) { - return this.parse().finally(onfinally); + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); } } -class APIClient { - constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes - httpAgent, fetch: overriddenFetch, }) { - this.baseURL = baseURL; - this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); - this.timeout = validatePositiveInteger('timeout', timeout); - this.httpAgent = httpAgent; - this.fetch = overriddenFetch ?? registry_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(async (opts) => { - const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer()) - : opts?.body instanceof DataView ? opts.body - : opts?.body instanceof ArrayBuffer ? new DataView(opts.body) - : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer) - : opts?.body; - return { method, path, ...opts, body }; - })); - } - 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(); - } - } - else if (ArrayBuffer.isView(body)) { - return body.byteLength.toString(); - } - return null; - } - buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, headers: headers = {} } = options; - const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ? - options.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); - options.timeout = options.timeout ?? this.timeout; - const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url); - const minAgentTimeout = options.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 (!inputOptions.idempotencyKey) - inputOptions.idempotencyKey = this.defaultIdempotencyKey(); - headers[this.idempotencyHeader] = inputOptions.idempotencyKey; - } - const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount }); - 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: options.timeout }; - } - buildHeaders({ options, headers, contentLength, retryCount, }) { - 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) && kind !== 'node') { - delete reqHeaders['content-type']; - } - // Don't set theses headers if they were already set or removed through default headers or by the caller. - // We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to account - // for the removal case. - if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined && - getHeader(headers, 'x-stainless-retry-count') === undefined) { - reqHeaders['x-stainless-retry-count'] = String(retryCount); - } - if (getHeader(defaultHeaders, 'x-stainless-timeout') === undefined && - getHeader(headers, 'x-stainless-timeout') === undefined && - options.timeout) { - reqHeaders['x-stainless-timeout'] = String(Math.trunc(options.timeout / 1000)); - } - 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; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); - 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 error_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); - const fetchOptions = { - signal: controller.signal, - ...options, - }; - if (fetchOptions.method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = fetchOptions.method.toUpperCase(); - } - return ( - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - this.fetch.call(undefined, url, fetchOptions).finally(() => { - clearTimeout(timeout); - })); - } - 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; +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = new WeakMap(); +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; } -class AbstractPage { - constructor(client, response, body, options) { - _AbstractPage_client.set(this, void 0); - core_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_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 core_classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); +const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals } - 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; - } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); } - async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; } + delete details.retryOfRequestLogID; } -} + return details; +}; +//# sourceMappingURL=log.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/version.mjs +const VERSION = '5.3.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/detect-platform.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; /** - * 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) - * } + * Note this does not detect 'browser'; for that, use getBrowserInfo(). */ -class PagePromise extends APIPromise { - constructor(client, request, Page) { - super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options)); +function getDetectedPlatform() { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; } - /** - * 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; - } + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; } + if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { + return 'node'; + } + return 'unknown'; } -const 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, - __metadata: true, - __binaryRequest: true, - __binaryResponse: true, - __streamClass: true, -}; -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) { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === 'deno') { return { 'X-Stainless-Lang': 'js', 'X-Stainless-Package-Version': VERSION, @@ -70673,18 +62671,18 @@ const getPlatformProperties = () => { 'X-Stainless-OS': 'Unknown', 'X-Stainless-Arch': `other:${EdgeRuntime}`, 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': process.version, + 'X-Stainless-Runtime-Version': globalThis.process.version, }; } // Check if Node.js - if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + if (detectedPlatform === 'node') { return { 'X-Stainless-Lang': 'js', 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(process.platform), - 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'), 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': process.version, + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', }; } const browserInfo = getBrowserInfo(); @@ -70784,697 +62782,756 @@ let _platformHeaders; const getPlatformHeaders = () => { return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); }; -const safeJSON = (text) => { - try { - return JSON.parse(text); - } - catch (err) { - return undefined; - } -}; -// https://url.spec.whatwg.org/#url-scheme-string -const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const isAbsoluteURL = (url) => { - return startsWithSchemeRegexp.test(url); -}; -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -const validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_OpenAIError(`${name} must be an integer`); - } - if (n < 0) { - throw new error_OpenAIError(`${name} must be a positive integer`); +//# sourceMappingURL=detect-platform.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/shims.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; } - return n; -}; -const castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - return new Error(JSON.stringify(err)); - } - catch { } + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); } - return new Error(err); -}; -const ensurePresent = (value) => { - if (value == null) - throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); - return value; -}; + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } + else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + }, + }); +} /** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 */ -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; -}; -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`); -}; -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`); -}; -const coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const maybeCoerceInteger = (value) => { - if (value === undefined) { - return undefined; +function ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; } - return coerceInteger(value); + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//# sourceMappingURL=shims.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/request-options.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; }; -const maybeCoerceFloat = (value) => { - if (value === undefined) { - return undefined; - } - return coerceFloat(value); +//# sourceMappingURL=request-options.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs +const default_format = 'RFC3986'; +const formatters = { + RFC1738: (v) => String(v).replace(/%20/g, '+'), + RFC3986: (v) => String(v), }; -const maybeCoerceBoolean = (value) => { - if (value === undefined) { - return undefined; +const RFC1738 = 'RFC1738'; +const RFC3986 = 'RFC3986'; +//# sourceMappingURL=formats.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs + +const has = Object.prototype.hasOwnProperty; +const is_array = Array.isArray; +const hex_table = (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } - return coerceBoolean(value); -}; -// https://stackoverflow.com/a/34491287 -function isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -/** - * 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) + return array; +})(); +function compact_queue(queue) { + while (queue.length > 1) { + const item = queue.pop(); + if (!item) continue; - const val = newHeaders[k]; - if (val === null) { - delete targetHeaders[lowerKey]; + const obj = item.obj[item.prop]; + if (is_array(obj)) { + const compacted = []; + for (let j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + // @ts-ignore + item.obj[item.prop] = compacted; } - else if (val !== undefined) { - targetHeaders[lowerKey] = val; + } +} +function array_to_object(source, options) { + const obj = options && options.plainObjects ? Object.create(null) : {}; + for (let i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; } } + return obj; } -const SENSITIVE_HEADERS = new Set(['authorization', 'api-key']); -function debug(action, ...args) { - if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') { - const modifiedArgs = args.map((arg) => { - if (!arg) { - return arg; +function merge(target, source, options = {}) { + if (!source) { + return target; + } + if (typeof source !== 'object') { + if (is_array(target)) { + target.push(source); + } + else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || + !has.call(Object.prototype, source)) { + target[source] = true; } - // Check for sensitive headers in request body 'headers' object - if (arg['headers']) { - // clone so we don't mutate - const modifiedArg = { ...arg, headers: { ...arg['headers'] } }; - for (const header in arg['headers']) { - if (SENSITIVE_HEADERS.has(header.toLowerCase())) { - modifiedArg['headers'][header] = 'REDACTED'; - } + } + else { + return [target, source]; + } + return target; + } + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + let mergeTarget = target; + if (is_array(target) && !is_array(source)) { + // @ts-ignore + mergeTarget = array_to_object(target, options); + } + if (is_array(target) && is_array(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + const targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); } - return modifiedArg; - } - let modifiedArg = null; - // Check for sensitive headers in headers object - for (const header in arg) { - if (SENSITIVE_HEADERS.has(header.toLowerCase())) { - // avoid making a copy until we need to - modifiedArg ?? (modifiedArg = { ...arg }); - modifiedArg[header] = 'REDACTED'; + else { + target.push(item); } } - return modifiedArg ?? arg; + else { + target[i] = item; + } }); - console.log(`OpenAI:DEBUG:${action}`, ...modifiedArgs); + return target; } -} -/** - * 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'); -}; -const isHeadersProtocol = (headers) => { - return typeof headers?.get === 'function'; -}; -const getRequiredHeader = (headers, header) => { - const foundHeader = getHeader(headers, header); - if (foundHeader === undefined) { - throw new Error(`Could not find ${header} header`); - } - return foundHeader; -}; -const getHeader = (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; - } + return Object.keys(source).reduce(function (acc, key) { + const value = source[key]; + if (has.call(acc, key)) { + acc[key] = merge(acc[key], value, options); } - } - 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; + else { + acc[key] = value; } + return acc; + }, mergeTarget); +} +function assign_single_source(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +} +function decode(str, _, charset) { + const strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } - return undefined; -}; -/** - * Encodes a string to Base64 format. - */ -const toBase64 = (str) => { - if (!str) - return ''; - if (typeof Buffer !== 'undefined') { - return Buffer.from(str).toString('base64'); + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); } - if (typeof btoa !== 'undefined') { - return btoa(str); + catch (e) { + return strWithoutPlus; } - throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); -}; -/** - * Converts a Base64 encoded string to a Float32Array. - * @param base64Str - The Base64 encoded string. - * @returns An Array of numbers interpreted as Float32 values. - */ -const toFloat32Array = (base64Str) => { - if (typeof Buffer !== 'undefined') { - // for Node.js environment - const buf = Buffer.from(base64Str, 'base64'); - return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); +} +const limit = 1024; +const encode = (str, _defaultEncoder, charset, _kind, format) => { + // This code was originally written by Brian White for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; } - else { - // for legacy web platform APIs - const binaryStr = atob(base64Str); - const len = binaryStr.length; - const bytes = new Uint8Array(len); - for (let i = 0; i < len; i++) { - bytes[i] = binaryStr.charCodeAt(i); + let string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } + else if (typeof str !== 'string') { + string = String(str); + } + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + let out = ''; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 0x2d || // - + c === 0x2e || // . + c === 0x5f || // _ + c === 0x7e || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5a) || // a-z + (c >= 0x61 && c <= 0x7a) || // A-Z + (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 0x80) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 0x800) { + arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)]; + continue; + } + if (c < 0xd800 || c >= 0xe000) { + arr[arr.length] = + hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; + continue; + } + i += 1; + c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); + arr[arr.length] = + hex_table[0xf0 | (c >> 18)] + + hex_table[0x80 | ((c >> 12) & 0x3f)] + + hex_table[0x80 | ((c >> 6) & 0x3f)] + + hex_table[0x80 | (c & 0x3f)]; } - return Array.from(new Float32Array(bytes.buffer)); + out += arr.join(''); } + return out; }; -function isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); -} -//# sourceMappingURL=core.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resource.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class APIResource { - constructor(client) { - this._client = client; +function compact(value) { + const queue = [{ obj: { o: value }, prop: 'o' }]; + const refs = []; + for (let i = 0; i < queue.length; ++i) { + const item = queue[i]; + // @ts-ignore + const obj = item.obj[item.prop]; + const keys = Object.keys(obj); + for (let j = 0; j < keys.length; ++j) { + const key = keys[j]; + const val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } } + compact_queue(queue); + return value; } -//# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Completions extends APIResource { - create(body, options) { - return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); +function is_regexp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} +function is_buffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); } -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Messages extends APIResource { - list(completionId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(completionId, {}, query); +function combine(a, b) { + return [].concat(a, b); +} +function maybe_map(val, fn) { + if (is_array(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); } - return this._client.getAPIList(`/chat/completions/${completionId}/messages`, ChatCompletionStoreMessagesPage, { query, ...options }); + return mapped; } + return fn(val); } +//# sourceMappingURL=utils.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class Page extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.object = body.object; - } - getPaginatedItems() { - return this.data ?? []; +const stringify_has = Object.prototype.hasOwnProperty; +const array_prefix_generators = { + brackets(prefix) { + return String(prefix) + '[]'; + }, + comma: 'comma', + indices(prefix, key) { + return String(prefix) + '[' + key + ']'; + }, + repeat(prefix) { + return String(prefix); + }, +}; +const stringify_is_array = Array.isArray; +const push = Array.prototype.push; +const push_to_array = function (arr, value_or_array) { + push.apply(arr, stringify_is_array(value_or_array) ? value_or_array : [value_or_array]); +}; +const to_ISO = Date.prototype.toISOString; +const defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: formatters[default_format], + /** @deprecated */ + indices: false, + serializeDate(date) { + return to_ISO.call(date); + }, + skipNulls: false, + strictNullHandling: false, +}; +function is_non_nullish_primitive(v) { + return (typeof v === 'string' || + typeof v === 'number' || + typeof v === 'boolean' || + typeof v === 'symbol' || + typeof v === 'bigint'); +} +const sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { + // Where object last appeared in the ref tree + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } + else { + find_flag = true; // Break while + } + } + if (typeof tmp_sc.get(sentinel) === 'undefined') { + step = 0; + } } - // @deprecated Please use `nextPageInfo()` instead - /** - * This page represents a response that isn't actually paginated at the API level - * so there will never be any next page params. - */ - nextPageParams() { - return null; + if (typeof filter === 'function') { + obj = filter(prefix, obj); } - nextPageInfo() { - return null; + else if (obj instanceof Date) { + obj = serializeDate?.(obj); } -} -class CursorPage extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; + else if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { + obj = maybe_map(obj, function (value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); } - getPaginatedItems() { - return this.data ?? []; + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, 'key', format) + : prefix; + } + obj = ''; } - hasNextPage() { - if (this.has_more === false) { - return false; + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix + // @ts-expect-error + : encoder(prefix, defaults.encoder, charset, 'key', format); + return [ + formatter?.(key_value) + + '=' + + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), + ]; } - return super.hasNextPage(); + return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; } - // @deprecated Please use `nextPageInfo()` instead - nextPageParams() { - const info = this.nextPageInfo(); - if (!info) - return null; - if ('params' in info) - return info.params; - const params = Object.fromEntries(info.url.searchParams); - if (!Object.keys(params).length) - return null; - return params; + const values = []; + if (typeof obj === 'undefined') { + return values; } - nextPageInfo() { - const data = this.getPaginatedItems(); - if (!data.length) { - return null; + let obj_keys; + if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + // @ts-expect-error values only + obj = maybe_map(obj, encoder); } - const id = data[data.length - 1]?.id; - if (!id) { - return null; + obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } + else if (stringify_is_array(filter)) { + obj_keys = filter; + } + else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + const adjusted_prefix = commaRoundTrip && stringify_is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; + if (allowEmptyArrays && stringify_is_array(obj) && obj.length === 0) { + return adjusted_prefix + '[]'; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = + // @ts-ignore + typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; } - return { params: { after: id } }; + // @ts-ignore + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; + const key_prefix = stringify_is_array(obj) ? + typeof generateArrayPrefix === 'function' ? + generateArrayPrefix(adjusted_prefix, encoded_key) + : adjusted_prefix + : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); + sideChannel.set(object, step); + const valueSideChannel = new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === 'comma' && encodeValuesOnly && stringify_is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); } + return values; } -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class completions_Completions extends APIResource { - constructor() { - super(...arguments); - this.messages = new Messages(this._client); +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); } - create(body, options) { - return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); } - /** - * Get a stored chat completion. Only Chat Completions that have been created with - * the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * const chatCompletion = - * await client.chat.completions.retrieve('completion_id'); - * ``` - */ - retrieve(completionId, options) { - return this._client.get(`/chat/completions/${completionId}`, options); + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); } - /** - * Modify a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be modified. Currently, the only - * supported modification is to update the `metadata` field. - * - * @example - * ```ts - * const chatCompletion = await client.chat.completions.update( - * 'completion_id', - * { metadata: { foo: 'string' } }, - * ); - * ``` - */ - update(completionId, body, options) { - return this._client.post(`/chat/completions/${completionId}`, { body, ...options }); + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); + let format = default_format; + if (typeof opts.format !== 'undefined') { + if (!stringify_has.call(formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); } - return this._client.getAPIList('/chat/completions', ChatCompletionsPage, { query, ...options }); + format = opts.format; } - /** - * Delete a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be deleted. - * - * @example - * ```ts - * const chatCompletionDeleted = - * await client.chat.completions.del('completion_id'); - * ``` - */ - del(completionId, options) { - return this._client.delete(`/chat/completions/${completionId}`, options); + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === 'function' || stringify_is_array(opts.filter)) { + filter = opts.filter; } -} -class ChatCompletionsPage extends CursorPage { -} -class ChatCompletionStoreMessagesPage extends CursorPage { -} -completions_Completions.ChatCompletionsPage = ChatCompletionsPage; -completions_Completions.Messages = Messages; -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Chat extends APIResource { - constructor() { - super(...arguments); - this.completions = new completions_Completions(this._client); + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; } -} -Chat.Completions = completions_Completions; -Chat.ChatCompletionsPage = ChatCompletionsPage; -//# sourceMappingURL=chat.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Embeddings extends APIResource { - /** - * Creates an embedding vector representing the input text. - * - * @example - * ```ts - * const createEmbeddingResponse = - * await client.embeddings.create({ - * input: 'The quick brown fox jumped over the lazy dog', - * model: 'text-embedding-3-small', - * }); - * ``` - */ - create(body, options) { - const hasUserProvidedEncodingFormat = !!body.encoding_format; - // No encoding_format specified, defaulting to base64 for performance reasons - // See https://github.com/openai/openai-node/pull/1312 - let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; - if (hasUserProvidedEncodingFormat) { - debug('Request', 'User defined encoding_format:', body.encoding_format); - } - const response = this._client.post('/embeddings', { - body: { - ...body, - encoding_format: encoding_format, - }, - ...options, - }); - // if the user specified an encoding_format, return the response as-is - if (hasUserProvidedEncodingFormat) { - return response; - } - // in this stage, we are sure the user did not specify an encoding_format - // and we defaulted to base64 for performance reasons - // we are sure then that the response is base64 encoded, let's decode it - // the returned result will be a float32 array since this is OpenAI API's default encoding - debug('response', 'Decoding base64 embeddings to float32 array'); - return response._thenUnwrap((response) => { - if (response && response.data) { - response.data.forEach((embeddingBase64Obj) => { - const embeddingBase64Str = embeddingBase64Obj.embedding; - embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); - }); - } - return response; - }); + else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } + else { + arrayFormat = defaults.arrayFormat; } + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + const allowDots = typeof opts.allowDots === 'undefined' ? + !!opts.encodeDotInKeys === true ? + true + : defaults.allowDots + : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, + }; } -//# sourceMappingURL=embeddings.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class Files extends APIResource { - /** - * Upload a file that can be used across various endpoints. Individual files can be - * up to 512 MB, and the size of all files uploaded by one organization can be up - * to 100 GB. - * - * The Assistants API supports files up to 2 million tokens and of specific file - * types. See the - * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for - * details. - * - * The Fine-tuning API only supports `.jsonl` files. The input also has certain - * required formats for fine-tuning - * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or - * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) - * models. - * - * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also - * has a specific required - * [format](https://platform.openai.com/docs/api-reference/batch/request-input). - * - * Please [contact us](https://help.openai.com/) if you need to increase these - * storage limits. - */ - create(body, options) { - return this._client.post('/files', multipartFormRequestOptions({ body, ...options })); +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); } - /** - * Returns information about a specific file. - */ - retrieve(fileId, options) { - return this._client.get(`/files/${fileId}`, options); + else if (stringify_is_array(options.filter)) { + filter = options.filter; + obj_keys = filter; } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/files', FileObjectsPage, { query, ...options }); + const keys = []; + if (typeof obj !== 'object' || obj === null) { + return ''; } - /** - * Delete a file. - */ - del(fileId, options) { - return this._client.delete(`/files/${fileId}`, options); + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); } - /** - * Returns the contents of the specified file. - */ - content(fileId, options) { - return this._client.get(`/files/${fileId}/content`, { - ...options, - headers: { Accept: 'application/binary', ...options?.headers }, - __binaryResponse: true, - }); + if (options.sort) { + obj_keys.sort(options.sort); } - /** - * Returns the contents of the specified file. - * - * @deprecated The `.content()` method should be used instead - */ - retrieveContent(fileId, options) { - return this._client.get(`/files/${fileId}/content`, options); + const sideChannel = new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify(obj[key], key, + // @ts-expect-error + generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); } - /** - * Waits for the given file to be processed, default timeout is 30 mins. - */ - async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { - const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); - const start = Date.now(); - let file = await this.retrieve(id); - while (!file.status || !TERMINAL_STATES.has(file.status)) { - await sleep(pollInterval); - file = await this.retrieve(id); - if (Date.now() - start > maxWait) { - throw new APIConnectionTimeoutError({ - message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, - }); - } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? '?' : ''; + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } + else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; } - return file; } + return joined.length > 0 ? prefix + joined : ''; } -class FileObjectsPage extends CursorPage { -} -Files.FileObjectsPage = FileObjectsPage; -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +//# sourceMappingURL=stringify.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/index.mjs +const formats = { + formatters: formatters, + RFC1738: RFC1738, + RFC3986: RFC3986, + default: default_format, +}; -class Images extends APIResource { - /** - * Creates a variation of a given image. This endpoint only supports `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.createVariation({ - * image: fs.createReadStream('otter.png'), - * }); - * ``` - */ - createVariation(body, options) { - return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options })); - } - /** - * Creates an edited or extended image given one or more source images and a - * prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.edit({ - * image: fs.createReadStream('path/to/file'), - * prompt: 'A cute baby sea otter wearing a beret', - * }); - * ``` - */ - edit(body, options) { - return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options })); + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/bytes.mjs +function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; } - /** - * Creates an image given a prompt. - * [Learn more](https://platform.openai.com/docs/guides/images). - * - * @example - * ```ts - * const imagesResponse = await client.images.generate({ - * prompt: 'A cute baby sea otter', - * }); - * ``` - */ - generate(body, options) { - return this._client.post('/images/generations', { body, ...options }); + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; } + return output; } -//# sourceMappingURL=images.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Speech extends APIResource { - /** - * Generates audio from the input text. - * - * @example - * ```ts - * const speech = await client.audio.speech.create({ - * input: 'input', - * model: 'string', - * voice: 'ash', - * }); - * - * const content = await speech.blob(); - * console.log(content); - * ``` - */ - create(body, options) { - return this._client.post('/audio/speech', { - body, - ...options, - headers: { Accept: 'application/octet-stream', ...options?.headers }, - __binaryResponse: true, - }); - } +let encodeUTF8_; +function bytes_encodeUTF8(str) { + let encoder; + return (encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); } -//# sourceMappingURL=speech.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +let decodeUTF8_; +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); +} +//# sourceMappingURL=bytes.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/decoders/line.mjs +var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; -class Transcriptions extends APIResource { - create(body, options) { - return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ - body, - ...options, - stream: body.stream ?? false, - __metadata: { model: body.model }, - })); +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class LineDecoder { + constructor() { + _LineDecoder_buffer.set(this, void 0); + _LineDecoder_carriageReturnIndex.set(this, void 0); + __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) + : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + // skip until we either get a corresponding `\n`, a new `\r` or nothing + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + // we got double \r or \rtext\n + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && + (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { + return []; + } + return this.decode('\n'); } } -//# sourceMappingURL=transcriptions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Translations extends APIResource { - create(body, options) { - return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } })); +_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap(); +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** + * This function searches the buffer for the end patterns, (\r or \n) + * and returns an object with the index preceding the matched newline and the + * index after the newline char. `null` is returned if no new line is found. + * + * ```ts + * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } + * ``` + */ +function findNewlineIndex(buffer, startIndex) { + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) { + return { preceding: i, index: i + 1, carriage: false }; + } + if (buffer[i] === carriage) { + return { preceding: i, index: i + 1, carriage: true }; + } } + return null; } -//# sourceMappingURL=translations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; +} +//# sourceMappingURL=line.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/streaming.mjs @@ -71482,864 +63539,845 @@ class Translations extends APIResource { -class Audio extends APIResource { - constructor() { - super(...arguments); - this.transcriptions = new Transcriptions(this._client); - this.translations = new Translations(this._client); - this.speech = new Speech(this._client); +class Stream { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; } -} -Audio.Transcriptions = Transcriptions; -Audio.Translations = Translations; -Audio.Speech = Speech; -//# sourceMappingURL=audio.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Moderations extends APIResource { - /** - * Classifies if text and/or image inputs are potentially harmful. Learn more in - * the [moderation guide](https://platform.openai.com/docs/guides/moderation). - */ - create(body, options) { - return this._client.post('/moderations', { body, ...options }); + static fromSSEResponse(response, controller) { + let consumed = false; + async function* iterator() { + if (consumed) { + throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (done) + continue; + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + if (sse.event === null || + sse.event.startsWith('response.') || + sse.event.startsWith('transcript.')) { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + if (data && data.error) { + throw new APIError(undefined, data.error, undefined, response.headers); + } + yield data; + } + else { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + // TODO: Is this where the error should be thrown? + if (sse.event == 'error') { + throw new APIError(undefined, data.error, data.message, undefined); + } + yield { event: sse.event, data: data }; + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); } -} -//# sourceMappingURL=moderations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Models extends APIResource { /** - * Retrieves a model instance, providing basic information about the model such as - * the owner and permissioning. + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. */ - retrieve(model, options) { - return this._client.get(`/models/${model}`, options); + static fromReadableStream(readableStream, controller) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller); + } + [Symbol.asyncIterator]() { + return this.iterator(); } /** - * Lists the currently available models, and provides basic information about each - * one such as the owner and availability. + * Splits the stream into two streams which can be + * independently read from at different speeds. */ - list(options) { - return this._client.getAPIList('/models', ModelsPage, options); + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new Stream(() => teeIterator(left), this.controller), + new Stream(() => teeIterator(right), this.controller), + ]; } /** - * Delete a fine-tuned model. You must have the Owner role in your organization to - * delete a model. + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. */ - del(model, options) { - return this._client.delete(`/models/${model}`, options); + toReadableStream() { + const self = this; + let iter; + return makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = bytes_encodeUTF8(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new error_OpenAIError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; } } /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. */ -class ModelsPage extends Page { -} -Models.ModelsPage = ModelsPage; -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Methods extends APIResource { +async function* iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } } -//# sourceMappingURL=methods.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Graders extends APIResource { - /** - * Run a grader. - * - * @example - * ```ts - * const response = await client.fineTuning.alpha.graders.run({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * model_sample: 'model_sample', - * reference_answer: 'string', - * }); - * ``` - */ - run(body, options) { - return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; } - /** - * Validate a grader. - * - * @example - * ```ts - * const response = - * await client.fineTuning.alpha.graders.validate({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * }); - * ``` - */ - validate(body, options) { - return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); +} +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; } + return [str, '', '']; } -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/parse.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Alpha extends APIResource { - constructor() { - super(...arguments); - this.graders = new Graders(this._client); +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const json = await response.json(); + return addRequestID(json, response); + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + })); + return body; +} +function addRequestID(value, response) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return value; } + return Object.defineProperty(value, '_request_id', { + value: response.headers.get('x-request-id'), + enumerable: false, + }); } -Alpha.Graders = Graders; -//# sourceMappingURL=alpha.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +//# sourceMappingURL=parse.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/api-promise.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _APIPromise_client; - -class Permissions extends APIResource { +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } /** - * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * Gets the raw `Response` instance instead of parsing the response + * data. * - * This enables organization owners to share fine-tuned models with other projects - * in their organization. + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * { project_ids: ['string'] }, - * )) { - * // ... - * } - * ``` + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. */ - create(fineTunedModelCheckpoint, body, options) { - return this._client.getAPIList(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, PermissionCreateResponsesPage, { body, method: 'post', ...options }); - } - retrieve(fineTunedModelCheckpoint, query = {}, options) { - if (isRequestOptions(query)) { - return this.retrieve(fineTunedModelCheckpoint, {}, query); - } - return this._client.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { - query, - ...options, - }); + asResponse() { + return this.responsePromise.then((p) => p.response); } /** - * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the X-Request-ID header which is useful for debugging requests and reporting + * issues to OpenAI. * - * Organization owners can use this endpoint to delete a permission for a - * fine-tuned model checkpoint. + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. * - * @example - * ```ts - * const permission = - * await client.fineTuning.checkpoints.permissions.del( - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', - * ); - * ``` + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. */ - del(fineTunedModelCheckpoint, permissionId, options) { - return this._client.delete(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`, options); - } -} -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class PermissionCreateResponsesPage extends Page { -} -Permissions.PermissionCreateResponsesPage = PermissionCreateResponsesPage; -//# sourceMappingURL=permissions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Checkpoints extends APIResource { - constructor() { - super(...arguments); - this.permissions = new Permissions(this._client); + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get('x-request-id') }; } -} -Checkpoints.Permissions = Permissions; -Checkpoints.PermissionCreateResponsesPage = PermissionCreateResponsesPage; -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class checkpoints_Checkpoints extends APIResource { - list(fineTuningJobId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(fineTuningJobId, {}, query); + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); } - return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options }); + 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); } } -class FineTuningJobCheckpointsPage extends CursorPage { -} -checkpoints_Checkpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +_APIPromise_client = new WeakMap(); +//# sourceMappingURL=api-promise.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/pagination.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _AbstractPage_client; -class Jobs extends APIResource { - constructor() { - super(...arguments); - this.checkpoints = new checkpoints_Checkpoints(this._client); - } - /** - * Creates a fine-tuning job which begins the process of creating a new model from - * a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.create({ - * model: 'gpt-4o-mini', - * training_file: 'file-abc123', - * }); - * ``` - */ - create(body, options) { - return this._client.post('/fine_tuning/jobs', { body, ...options }); +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; } - /** - * Get info about a fine-tuning job. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.retrieve( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - retrieve(fineTuningJobId, options) { - return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new error_OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); } - return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options }); + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); } - /** - * Immediately cancel a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.cancel( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - cancel(fineTuningJobId, options) { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } } - listEvents(fineTuningJobId, query = {}, options) { - if (isRequestOptions(query)) { - return this.listEvents(fineTuningJobId, {}, query); + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } } - return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { - query, - ...options, - }); } - /** - * Pause a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.pause( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - pause(fineTuningJobId, options) { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`, options); +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); } /** - * Resume a fine-tune job. + * Allow auto-paginating iteration on an unawaited list call, eg: * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.resume( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` + * for await (const item of client.items.list()) { + * console.log(item) + * } */ - resume(fineTuningJobId, options) { - return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`, options); + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } } } -class FineTuningJobsPage extends CursorPage { -} -class FineTuningJobEventsPage extends CursorPage { -} -Jobs.FineTuningJobsPage = FineTuningJobsPage; -Jobs.FineTuningJobEventsPage = FineTuningJobEventsPage; -Jobs.Checkpoints = checkpoints_Checkpoints; -Jobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage; -//# sourceMappingURL=jobs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class FineTuning extends APIResource { - constructor() { - super(...arguments); - this.methods = new Methods(this._client); - this.jobs = new Jobs(this._client); - this.checkpoints = new Checkpoints(this._client); - this.alpha = new Alpha(this._client); +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class Page extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.object = body.object; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + return null; } } -FineTuning.Methods = Methods; -FineTuning.Jobs = Jobs; -FineTuning.FineTuningJobsPage = FineTuningJobsPage; -FineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage; -FineTuning.Checkpoints = Checkpoints; -FineTuning.Alpha = Alpha; -//# sourceMappingURL=fine-tuning.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class GraderModels extends APIResource { +class CursorPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const data = this.getPaginatedItems(); + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after: id, + }, + }; + } } -//# sourceMappingURL=grader-models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - +//# sourceMappingURL=pagination.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/uploads.mjs -class graders_Graders extends APIResource { - constructor() { - super(...arguments); - this.graderModels = new GraderModels(this._client); +const checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; + throw new Error('`File` is not defined as a global, which is required for file uploads.' + + (isOldNode ? + " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." + : '')); } +}; +/** + * Construct a `File` instance. This is used to ensure a helpful error is thrown + * for environments that don't define a global `File` yet. + */ +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? 'unknown_file', options); } -graders_Graders.GraderModels = GraderModels; -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs +function getName(value) { + return (((typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + '') + .split(/[\\/]/) + .pop() || undefined); +} +const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; /** - * Like `Promise.allSettled()` but throws an error if any promises are rejected. + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. */ -const allSettledWithThrow = async (promises) => { - const results = await Promise.allSettled(promises); - const rejected = results.filter((result) => result.status === 'rejected'); - if (rejected.length) { - for (const result of rejected) { - console.error(result.reason); +const maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await createForm(opts.body, fetch) }; +}; +const multipartFormRequestOptions = async (opts, fetch) => { + return { ...opts, body: await createForm(opts.body, fetch) }; +}; +const supportsFormDataMap = new WeakMap(); +/** + * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending + * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". + * This function detects if the fetch function provided supports the global FormData object to avoid + * confusing error messages later on. + */ +function supportsFormData(fetchObject) { + const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = ('Response' in fetch ? + fetch.Response + : (await fetch('data:,')).constructor); + const data = new FormData(); + if (data.toString() === (await new FetchResponse(data).text())) { + return false; + } + return true; } - throw new Error(`${rejected.length} promise(s) failed - see the above errors`); - } - // Note: TS was complaining about using `.filter().map()` here for some reason - const values = []; - for (const result of results) { - if (result.status === 'fulfilled') { - values.push(result.value); + catch { + // avoid false negatives + return true; } + })(); + supportsFormDataMap.set(fetch, promise); + return promise; +} +const createForm = async (body, fetch) => { + if (!(await supportsFormData(fetch))) { + throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); } - return values; + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; }; -//# sourceMappingURL=Util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class files_Files extends APIResource { - /** - * Create a vector store file by attaching a - * [File](https://platform.openai.com/docs/api-reference/files) to a - * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). - */ - create(vectorStoreId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/files`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Retrieves a vector store file. - */ - retrieve(vectorStoreId, fileId, options) { - return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); +// We check for Blob not File because Bun.File doesn't inherit from File, +// but they both inherit from Blob and have a `name` property at runtime. +const isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const isUploadable = (value) => typeof value === 'object' && + value !== null && + (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)); +const hasUploadableValue = (value) => { + if (isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) + return true; + } } - /** - * Update attributes on a vector store file. - */ - update(vectorStoreId, fileId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/files/${fileId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + return false; +}; +const addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); } - list(vectorStoreId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(vectorStoreId, {}, query); - } - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); } - /** - * Delete a vector store file. This will remove the file from the vector store but - * the file itself will not be deleted. To delete the file, use the - * [delete file](https://platform.openai.com/docs/api-reference/files/delete) - * endpoint. - */ - del(vectorStoreId, fileId, options) { - return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + else if (value instanceof Response) { + form.append(key, makeFile([await value.blob()], getName(value))); } - /** - * Attach a file to the given vector store and wait for it to be processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const file = await this.create(vectorStoreId, body, options); - return await this.poll(vectorStoreId, file.id, options); + else if (isAsyncIterable(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); } - /** - * Wait for the vector store file to finish processing. - * - * Note: this will return even if the file failed to process, you need to check - * file.last_error and file.status to handle these cases - */ - async poll(vectorStoreId, fileId, options) { - const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; - if (options?.pollIntervalMs) { - headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); - } - while (true) { - const fileResponse = await this.retrieve(vectorStoreId, fileId, { - ...options, - headers, - }).withResponse(); - const file = fileResponse.data; - switch (file.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep(sleepInterval); - break; - case 'failed': - case 'completed': - return file; - } - } + else if (isNamedBlob(value)) { + form.append(key, value, getName(value)); } - /** - * Upload a file to the `files` API and then attach it to the given vector store. - * - * Note the file will be asynchronously processed (you can use the alternative - * polling helper method to wait for processing to complete). - */ - async upload(vectorStoreId, file, options) { - const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); - return this.create(vectorStoreId, { file_id: fileInfo.id }, options); + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); } - /** - * Add a file to a vector store and poll until processing is complete. - */ - async uploadAndPoll(vectorStoreId, file, options) { - const fileInfo = await this.upload(vectorStoreId, file, options); - return await this.poll(vectorStoreId, fileInfo.id, options); + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); } - /** - * Retrieve the parsed contents of a vector store file. - */ - content(vectorStoreId, fileId, options) { - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files/${fileId}/content`, FileContentResponsesPage, { ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } }); + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); } -} -class VectorStoreFilesPage extends CursorPage { -} -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class FileContentResponsesPage extends Page { -} -files_Files.VectorStoreFilesPage = VectorStoreFilesPage; -files_Files.FileContentResponsesPage = FileContentResponsesPage; -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - +}; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/to-file.mjs -class FileBatches extends APIResource { - /** - * Create a vector store file batch. - */ - create(vectorStoreId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); +const isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function toFile(value, name, options) { + checkFileSupport(); + // If it's a promise, resolve it. + value = await value; + // If we've been given a `File` we don't need to do anything + if (isFileLike(value)) { + if (value instanceof File) { + return value; + } + return makeFile([await value.arrayBuffer()], value.name); } - /** - * Retrieves a vector store file batch. - */ - retrieve(vectorStoreId, batchId, options) { - return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); } - /** - * Cancel a vector store file batch. This attempts to cancel the processing of - * files in this batch as soon as possible. - */ - cancel(vectorStoreId, batchId, options) { - return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + const parts = await getBytes(value); + name || (name = getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; + } } - /** - * Create a vector store batch and poll until all files have been processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const batch = await this.create(vectorStoreId, body); - return await this.poll(vectorStoreId, batch.id, options); + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); } - listFiles(vectorStoreId, batchId, query = {}, options) { - if (isRequestOptions(query)) { - return this.listFiles(vectorStoreId, batchId, {}, query); - } - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } }); + else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); } - /** - * Wait for the given file batch to be processed. - * - * Note: this will return even if one of the files failed to process, you need to - * check batch.file_counts.failed_count to handle this case. - */ - async poll(vectorStoreId, batchId, options) { - const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; - if (options?.pollIntervalMs) { - headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); - } - while (true) { - const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, { - ...options, - headers, - }).withResponse(); - switch (batch.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep(sleepInterval); - break; - case 'failed': - case 'cancelled': - case 'completed': - return batch; - } + else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(...(await getBytes(chunk))); // TODO, consider validating? } } - /** - * Uploads the given files concurrently and then creates a vector store file batch. - * - * The concurrency limit is configurable using the `maxConcurrency` parameter. - */ - async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { - if (files == null || files.length == 0) { - throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); - } - const configuredConcurrency = options?.maxConcurrency ?? 5; - // We cap the number of workers at the number of files (so we don't start any unnecessary workers) - const concurrencyLimit = Math.min(configuredConcurrency, files.length); - const client = this._client; - const fileIterator = files.values(); - const allFileIds = [...fileIds]; - // This code is based on this design. The libraries don't accommodate our environment limits. - // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all - async function processFiles(iterator) { - for (let item of iterator) { - const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); - allFileIds.push(fileObj.id); - } - } - // Start workers to process results - const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); - // Wait for all processing to complete. - await allSettledWithThrow(workers); - return await this.createAndPoll(vectorStoreId, { - file_ids: allFileIds, - }); + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`); } + return parts; +} +function propsForError(value) { + if (typeof value !== 'object' || value === null) + return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; } +//# sourceMappingURL=to-file.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/uploads.mjs -//# sourceMappingURL=file-batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/resource.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class VectorStores extends APIResource { - constructor() { - super(...arguments); - this.files = new files_Files(this._client); - this.fileBatches = new FileBatches(this._client); - } - /** - * Create a vector store. - */ - create(body, options) { - return this._client.post('/vector_stores', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Retrieves a vector store. - */ - retrieve(vectorStoreId, options) { - return this._client.get(`/vector_stores/${vectorStoreId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Modifies a vector store. - */ - update(vectorStoreId, body, options) { - return this._client.post(`/vector_stores/${vectorStoreId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); +class APIResource { + constructor(client) { + this._client = client; } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); +} +//# sourceMappingURL=resource.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/path.mjs + +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; } - return this._client.getAPIList('/vector_stores', VectorStoresPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Delete a vector store. - */ - del(vectorStoreId, options) { - return this._client.delete(`/vector_stores/${vectorStoreId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + return (previousValue + + currentValue + + (index === params.length ? '' : (postPath ? encodeURIComponent : pathEncoder)(String(params[index])))); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegments = []; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, }); } - /** - * Search a vector store for relevant chunks based on a query and file attributes - * filter. - */ - search(vectorStoreId, body, options) { - return this._client.getAPIList(`/vector_stores/${vectorStoreId}/search`, VectorStoreSearchResponsesPage, { - body, - method: 'post', - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${path}\n${underline}`); } -} -class VectorStoresPage extends CursorPage { -} + return path; +}; /** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. */ -class VectorStoreSearchResponsesPage extends Page { -} -VectorStores.VectorStoresPage = VectorStoresPage; -VectorStores.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage; -VectorStores.Files = files_Files; -VectorStores.VectorStoreFilesPage = VectorStoreFilesPage; -VectorStores.FileContentResponsesPage = FileContentResponsesPage; -VectorStores.FileBatches = FileBatches; -//# sourceMappingURL=vector-stores.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/assistants.mjs +const path = createPathTagFunction(encodeURIPath); +//# sourceMappingURL=path.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Assistants extends APIResource { - /** - * Create an assistant with a model and instructions. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.create({ - * model: 'gpt-4o', - * }); - * ``` - */ - create(body, options) { - return this._client.post('/assistants', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Retrieves an assistant. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.retrieve( - * 'assistant_id', - * ); - * ``` - */ - retrieve(assistantId, options) { - return this._client.get(`/assistants/${assistantId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - /** - * Modifies an assistant. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.update( - * 'assistant_id', - * ); - * ``` - */ - update(assistantId, body, options) { - return this._client.post(`/assistants/${assistantId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/assistants', AssistantsPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } +class Messages extends APIResource { /** - * Delete an assistant. + * Get the messages in a stored chat completion. Only Chat Completions that have + * been created with the `store` parameter set to `true` will be returned. * * @example * ```ts - * const assistantDeleted = await client.beta.assistants.del( - * 'assistant_id', - * ); + * // Automatically fetches more pages as needed. + * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( + * 'completion_id', + * )) { + * // ... + * } * ``` */ - del(assistantId, options) { - return this._client.delete(`/assistants/${assistantId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + list(completionID, query = {}, options) { + return this._client.getAPIList(path `/chat/completions/${completionID}/messages`, (CursorPage), { query, ...options }); } } -class AssistantsPage extends CursorPage { -} -Assistants.AssistantsPage = AssistantsPage; -//# sourceMappingURL=assistants.mjs.map +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/error.mjs + +//# sourceMappingURL=error.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs function isRunnableFunctionWithParse(fn) { return typeof fn.parse === 'function'; } -/** - * This is helper class for passing a `function` and `parse` where the `function` - * argument type matches the `parse` return type. - * - * @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; - } -} /** * This is helper class for passing a `function` and `parse` where the `function` * argument type matches the `parse` return type. @@ -72355,9 +64393,6 @@ class ParsingToolFunction { const isAssistantMessage = (message) => { return message?.role === 'assistant'; }; -const isFunctionMessage = (message) => { - return message?.role === 'function'; -}; const isToolMessage = (message) => { return message?.role === 'tool'; }; @@ -72366,19 +64401,9 @@ function isPresent(obj) { } //# sourceMappingURL=chatCompletionUtils.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/EventStream.mjs -var EventStream_classPrivateFieldSet = (undefined && undefined.__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 EventStream_classPrivateFieldGet = (undefined && undefined.__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 _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; + class EventStream { constructor() { _EventStream_instances.add(this); @@ -72394,20 +64419,20 @@ class EventStream { _EventStream_errored.set(this, false); _EventStream_aborted.set(this, false); _EventStream_catchingPromiseCreated.set(this, false); - EventStream_classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { - EventStream_classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); - EventStream_classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); + __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); }), "f"); - EventStream_classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { - EventStream_classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); - EventStream_classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); + __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); }), "f"); // Don't let these promises cause unhandled rejection errors. // we will manually cause an unhandled rejection error later // if the user hasn't registered any error listener or called // any promise-returning method. - EventStream_classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); - EventStream_classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); } _run(executor) { // Unfortunately if we call `executor()` immediately we get runtime errors about @@ -72416,23 +64441,23 @@ class EventStream { executor().then(() => { this._emitFinal(); this._emit('end'); - }, EventStream_classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); + }, __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); }, 0); } _connected() { if (this.ended) return; - EventStream_classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); + __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); this._emit('connect'); } get ended() { - return EventStream_classPrivateFieldGet(this, _EventStream_ended, "f"); + return __classPrivateFieldGet(this, _EventStream_ended, "f"); } get errored() { - return EventStream_classPrivateFieldGet(this, _EventStream_errored, "f"); + return __classPrivateFieldGet(this, _EventStream_errored, "f"); } get aborted() { - return EventStream_classPrivateFieldGet(this, _EventStream_aborted, "f"); + return __classPrivateFieldGet(this, _EventStream_aborted, "f"); } abort() { this.controller.abort(); @@ -72445,7 +64470,7 @@ class EventStream { * @returns this ChatCompletionStream, so that calls can be chained */ on(event, listener) { - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); listeners.push({ listener }); return this; } @@ -72457,7 +64482,7 @@ class EventStream { * @returns this ChatCompletionStream, so that calls can be chained */ off(event, listener) { - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; if (!listeners) return this; const index = listeners.findIndex((l) => l.listener === listener); @@ -72471,7 +64496,7 @@ class EventStream { * @returns this ChatCompletionStream, so that calls can be chained */ once(event, listener) { - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); listeners.push({ listener, once: true }); return this; } @@ -72488,44 +64513,44 @@ class EventStream { */ emitted(event) { return new Promise((resolve, reject) => { - EventStream_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); if (event !== 'error') this.once('error', reject); this.once(event, resolve); }); } async done() { - EventStream_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - await EventStream_classPrivateFieldGet(this, _EventStream_endPromise, "f"); + __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _EventStream_endPromise, "f"); } _emit(event, ...args) { // make sure we don't emit any events after end - if (EventStream_classPrivateFieldGet(this, _EventStream_ended, "f")) { + if (__classPrivateFieldGet(this, _EventStream_ended, "f")) { return; } if (event === 'end') { - EventStream_classPrivateFieldSet(this, _EventStream_ended, true, "f"); - EventStream_classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); + __classPrivateFieldSet(this, _EventStream_ended, true, "f"); + __classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); } - const listeners = EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; if (listeners) { - EventStream_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + __classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); listeners.forEach(({ listener }) => listener(...args)); } if (event === 'abort') { const error = args[0]; - if (!EventStream_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { Promise.reject(error); } - EventStream_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - EventStream_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); this._emit('end'); return; } if (event === 'error') { // NOTE: _emit('error', error) should only be called from #handleError(). const error = args[0]; - if (!EventStream_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { // Trigger an unhandled rejection if the user hasn't registered any error handlers. // If you are seeing stack traces here, make sure to handle errors via either: // - runner.on('error', () => ...) @@ -72534,20 +64559,20 @@ class EventStream { // - etc. Promise.reject(error); } - EventStream_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - EventStream_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); this._emit('end'); } } _emitFinal() { } } _EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { - EventStream_classPrivateFieldSet(this, _EventStream_errored, true, "f"); + __classPrivateFieldSet(this, _EventStream_errored, true, "f"); if (error instanceof Error && error.name === 'AbortError') { error = new APIUserAbortError(); } if (error instanceof APIUserAbortError) { - EventStream_classPrivateFieldSet(this, _EventStream_aborted, true, "f"); + __classPrivateFieldSet(this, _EventStream_aborted, true, "f"); return this._emit('abort', error); } if (error instanceof error_OpenAIError) { @@ -72711,12 +64736,8 @@ function validateInputTools(tools) { } //# sourceMappingURL=parser.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs -var AbstractChatCompletionRunner_classPrivateFieldGet = (undefined && undefined.__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_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; + @@ -72744,17 +64765,14 @@ class AbstractChatCompletionRunner extends EventStream { this.messages.push(message); if (emit) { this._emit('message', message); - if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) { + if (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); + this._emit('functionToolCallResult', message.content); } else if (isAssistantMessage(message) && message.tool_calls) { for (const tool_call of message.tool_calls) { if (tool_call.type === 'function') { - this._emit('functionCall', tool_call.function); + this._emit('functionToolCall', tool_call.function); } } } @@ -72777,7 +64795,7 @@ class AbstractChatCompletionRunner extends EventStream { */ async finalContent() { await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); } /** * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, @@ -72785,23 +64803,23 @@ class AbstractChatCompletionRunner extends EventStream { */ async finalMessage() { await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + 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() { + async finalFunctionToolCall() { await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); } - async finalFunctionCallResult() { + async finalFunctionToolCallResult() { await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); } async totalUsage() { await this.done(); - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); } allChatCompletions() { return [...this._chatCompletions]; @@ -72810,20 +64828,20 @@ class AbstractChatCompletionRunner extends EventStream { const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (completion) this._emit('finalChatCompletion', completion); - const finalMessage = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); if (finalMessage) this._emit('finalMessage', finalMessage); - const finalContent = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); if (finalContent) this._emit('finalContent', finalContent); - const finalFunctionCall = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); if (finalFunctionCall) - this._emit('finalFunctionCall', finalFunctionCall); - const finalFunctionCallResult = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + this._emit('finalFunctionToolCall', finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); if (finalFunctionCallResult != null) - this._emit('finalFunctionCallResult', finalFunctionCallResult); + this._emit('finalFunctionToolCallResult', finalFunctionCallResult); if (this._chatCompletions.some((c) => c.usage)) { - this._emit('totalUsage', AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); } } async _createChatCompletion(client, params, options) { @@ -72833,7 +64851,7 @@ class AbstractChatCompletionRunner extends EventStream { this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } - AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); @@ -72844,70 +64862,6 @@ class AbstractChatCompletionRunner extends EventStream { } return await this._createChatCompletion(client, params, options); } - async _runFunctions(client, 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(client, { - ...restParams, - function_call, - functions, - messages: [...this.messages], - }, options); - const message = chatCompletion.choices[0]?.message; - if (!message) { - throw new error_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 = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); - this._addMessage({ role, name, content }); - if (singleFunctionToCall) - return; - } - } async _runTools(client, params, options) { const role = 'tool'; const { tool_choice = 'auto', stream, ...restParams } = params; @@ -72998,7 +64952,7 @@ class AbstractChatCompletionRunner extends EventStream { } // @ts-expect-error it can't rule out `never` type. const rawContent = await fn.function(parsed, this); - const content = AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, tool_call_id, content }); if (singleFunctionToCall) { return; @@ -73009,43 +64963,33 @@ class AbstractChatCompletionRunner extends EventStream { } } _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { - return AbstractChatCompletionRunner_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; + 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)) { - const { function_call, ...rest } = message; // TODO: support audio here const ret = { - ...rest, + ...message, content: message.content ?? null, refusal: message.refusal ?? null, }; - if (function_call) { - ret.function_call = function_call; - } return ret; } } throw new error_OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); -}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { +}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() { 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() { +}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() { 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 && typeof message.content === 'string' && @@ -73083,16 +65027,6 @@ _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletion class ChatCompletionRunner extends AbstractChatCompletionRunner { - /** @deprecated - please use `runTools` instead. */ - static runFunctions(client, params, options) { - const runner = new ChatCompletionRunner(); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, - }; - runner._run(() => runner._runFunctions(client, params, opts)); - return runner; - } static runTools(client, params, options) { const runner = new ChatCompletionRunner(); const opts = { @@ -73110,6 +65044,9 @@ class ChatCompletionRunner extends AbstractChatCompletionRunner { } } //# sourceMappingURL=ChatCompletionRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs + +//# sourceMappingURL=streaming.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs const STR = 0b000000001; const NUM = 0b000000010; @@ -73353,23 +65290,13 @@ const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); //# sourceMappingURL=parser.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs -var ChatCompletionStream_classPrivateFieldSet = (undefined && undefined.__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_classPrivateFieldGet = (undefined && undefined.__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 _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; + class ChatCompletionStream extends AbstractChatCompletionRunner { constructor(params) { super(); @@ -73377,11 +65304,11 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { _ChatCompletionStream_params.set(this, void 0); _ChatCompletionStream_choiceEventStates.set(this, void 0); _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); } get currentChatCompletionSnapshot() { - return ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); } /** * Intended for use on the frontend, consuming a stream produced with @@ -73408,16 +65335,16 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); this._connected(); for await (const chunk of stream) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return this._addChatCompletion(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } async _fromReadableStream(readableStream, options) { const signal = options?.signal; @@ -73426,29 +65353,29 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + __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(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); chatId = chunk.id; } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return this._addChatCompletion(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { if (this.ended) return; - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { - let state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; + let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; if (state) { return state; } @@ -73460,12 +65387,12 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { done_tool_calls: new Set(), current_tool_call_index: null, }; - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; + __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; return state; }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { if (this.ended) return; - const completion = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); this._emit('chunk', chunk, completion); for (const choice of chunk.choices) { const choiceSnapshot = completion.choices[choice.index]; @@ -73499,19 +65426,19 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { snapshot: choiceSnapshot.logprobs?.refusal ?? [], }); } - const state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); if (choiceSnapshot.finish_reason) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); if (state.current_tool_call_index != null) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); } } for (const toolCall of choice.delta.tool_calls ?? []) { if (state.current_tool_call_index !== toolCall.index) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); // new tool call started, the previous one is done if (state.current_tool_call_index != null) { - ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); } } state.current_tool_call_index = toolCall.index; @@ -73536,7 +65463,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { } } }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { - const state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); if (state.done_tool_calls.has(toolCallIndex)) { // we've already fired the done event return; @@ -73549,7 +65476,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { throw new Error('tool call snapshot missing `type`'); } if (toolCallSnapshot.type === 'function') { - const inputTool = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name); + const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name); this._emit('tool_calls.function.arguments.done', { name: toolCallSnapshot.function.name, index: toolCallIndex, @@ -73563,10 +65490,10 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { assertNever(toolCallSnapshot.type); } }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { - const state = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); if (choiceSnapshot.message.content && !state.content_done) { state.content_done = true; - const responseFormat = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); + const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); this._emit('content.done', { content: choiceSnapshot.message.content, parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, @@ -73588,25 +65515,25 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { if (this.ended) { throw new error_OpenAIError(`stream has ended, this shouldn't happen`); } - const snapshot = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); if (!snapshot) { throw new error_OpenAIError(`request ended without sending any chunks`); } - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); - return finalizeChatCompletion(snapshot, ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { - const responseFormat = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; + const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; if (isAutoParsableResponseFormat(responseFormat)) { return responseFormat; } return null; }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { var _a, _b, _c, _d; - let snapshot = ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); const { choices, ...rest } = chunk; if (!snapshot) { - snapshot = ChatCompletionStream_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { ...rest, choices: [], }, "f"); @@ -73639,7 +65566,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { } if (finish_reason) { choice.finish_reason = finish_reason; - if (ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { + if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { if (finish_reason === 'length') { throw new LengthFinishReasonError(); } @@ -73674,7 +65601,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { } if (content) { choice.message.content = (choice.message.content || '') + content; - if (!choice.message.refusal && ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { + if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { choice.message.parsed = partialParse(choice.message.content); } } @@ -73694,7 +65621,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { tool_call.function.name = fn.name; if (fn?.arguments) { tool_call.function.arguments += fn.arguments; - if (shouldParseToolCall(ChatCompletionStream_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { + if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments); } } @@ -73860,16 +65787,6 @@ class ChatCompletionStreamingRunner extends ChatCompletionStream { runner._run(() => runner._fromReadableStream(stream)); return runner; } - /** @deprecated - please use `runTools` instead. */ - static runFunctions(client, params, options) { - const runner = new ChatCompletionStreamingRunner(null); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, - }; - runner._run(() => runner._runFunctions(client, params, opts)); - return runner; - } static runTools(client, params, options) { const runner = new ChatCompletionStreamingRunner( // @ts-expect-error TODO these types are incompatible @@ -73883,7 +65800,7 @@ class ChatCompletionStreamingRunner extends ChatCompletionStream { } } //# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chat/completions.mjs +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -73894,7 +65811,71 @@ class ChatCompletionStreamingRunner extends ChatCompletionStream { -class chat_completions_Completions extends APIResource { +class Completions extends APIResource { + constructor() { + super(...arguments); + this.messages = new Messages(this._client); + } + create(body, options) { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); + } + /** + * Get a stored chat completion. Only Chat Completions that have been created with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * const chatCompletion = + * await client.chat.completions.retrieve('completion_id'); + * ``` + */ + retrieve(completionID, options) { + return this._client.get(path `/chat/completions/${completionID}`, options); + } + /** + * Modify a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be modified. Currently, the only + * supported modification is to update the `metadata` field. + * + * @example + * ```ts + * const chatCompletion = await client.chat.completions.update( + * 'completion_id', + * { metadata: { foo: 'string' } }, + * ); + * ``` + */ + update(completionID, body, options) { + return this._client.post(path `/chat/completions/${completionID}`, { body, ...options }); + } + /** + * List stored Chat Completions. Only Chat Completions that have been stored with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletion of client.chat.completions.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/chat/completions', (CursorPage), { query, ...options }); + } + /** + * Delete a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be deleted. + * + * @example + * ```ts + * const chatCompletionDeleted = + * await client.chat.completions.delete('completion_id'); + * ``` + */ + delete(completionID, options) { + return this._client.delete(path `/chat/completions/${completionID}`, options); + } parse(body, options) { validateInputTools(body.tools); return this._client.chat.completions @@ -73902,17 +65883,11 @@ class chat_completions_Completions extends APIResource { ...options, headers: { ...options?.headers, - 'X-Stainless-Helper-Method': 'beta.chat.completions.parse', + 'X-Stainless-Helper-Method': 'chat.completions.parse', }, }) ._thenUnwrap((completion) => parseChatCompletion(completion, body)); } - runFunctions(body, options) { - if (body.stream) { - return ChatCompletionStreamingRunner.runFunctions(this._client, body, options); - } - return ChatCompletionRunner.runFunctions(this._client, body, options); - } runTools(body, options) { if (body.stream) { return ChatCompletionStreamingRunner.runTools(this._client, body, options); @@ -73926,24 +65901,317 @@ class chat_completions_Completions extends APIResource { return ChatCompletionStream.createChatCompletion(this._client, body, options); } } + + + + +Completions.Messages = Messages; //# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chat/chat.mjs +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class chat_Chat extends APIResource { + +class Chat extends APIResource { constructor() { super(...arguments); - this.completions = new chat_completions_Completions(this._client); + this.completions = new Completions(this._client); } } -(function (Chat) { - Chat.Completions = chat_completions_Completions; -})(chat_Chat || (chat_Chat = {})); +Chat.Completions = Completions; //# sourceMappingURL=chat.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/headers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const brand_privateNullableHeaders = Symbol('brand.privateNullableHeaders'); +const isArray = Array.isArray; +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Speech extends APIResource { + /** + * Generates audio from the input text. + * + * @example + * ```ts + * const speech = await client.audio.speech.create({ + * input: 'input', + * model: 'string', + * voice: 'ash', + * }); + * + * const content = await speech.blob(); + * console.log(content); + * ``` + */ + create(body, options) { + return this._client.post('/audio/speech', { + body, + ...options, + headers: buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]), + __binaryResponse: true, + }); + } +} +//# sourceMappingURL=speech.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Transcriptions extends APIResource { + create(body, options) { + return this._client.post('/audio/transcriptions', multipartFormRequestOptions({ + body, + ...options, + stream: body.stream ?? false, + __metadata: { model: body.model }, + }, this._client)); + } +} +//# sourceMappingURL=transcriptions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Translations extends APIResource { + create(body, options) { + return this._client.post('/audio/translations', multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client)); + } +} +//# sourceMappingURL=translations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Audio extends APIResource { + constructor() { + super(...arguments); + this.transcriptions = new Transcriptions(this._client); + this.translations = new Translations(this._client); + this.speech = new Speech(this._client); + } +} +Audio.Transcriptions = Transcriptions; +Audio.Translations = Translations; +Audio.Speech = Speech; +//# sourceMappingURL=audio.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Batches extends APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body, options) { + return this._client.post('/batches', { body, ...options }); + } + /** + * Retrieves a batch. + */ + retrieve(batchID, options) { + return this._client.get(path `/batches/${batchID}`, options); + } + /** + * List your organization's batches. + */ + list(query = {}, options) { + return this._client.getAPIList('/batches', (CursorPage), { query, ...options }); + } + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to + * 10 minutes, before changing to `cancelled`, where it will have partial results + * (if any) available in the output file. + */ + cancel(batchID, options) { + return this._client.post(path `/batches/${batchID}/cancel`, options); + } +} +//# sourceMappingURL=batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/assistants.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Assistants extends APIResource { + /** + * Create an assistant with a model and instructions. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.create({ + * model: 'gpt-4o', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/assistants', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves an assistant. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.retrieve( + * 'assistant_id', + * ); + * ``` + */ + retrieve(assistantID, options) { + return this._client.get(path `/assistants/${assistantID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies an assistant. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.update( + * 'assistant_id', + * ); + * ``` + */ + update(assistantID, body, options) { + return this._client.post(path `/assistants/${assistantID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of assistants. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const assistant of client.beta.assistants.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/assistants', (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete an assistant. + * + * @example + * ```ts + * const assistantDeleted = + * await client.beta.assistants.delete('assistant_id'); + * ``` + */ + delete(assistantID, options) { + return this._client.delete(path `/assistants/${assistantID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=assistants.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/sessions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + class Sessions extends APIResource { /** * Create an ephemeral API token for use in client-side applications with the @@ -73964,7 +66232,7 @@ class Sessions extends APIResource { return this._client.post('/realtime/sessions', { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } } @@ -73972,6 +66240,7 @@ class Sessions extends APIResource { ;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/transcription-sessions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + class TranscriptionSessions extends APIResource { /** * Create an ephemeral API token for use in client-side applications with the @@ -73992,41 +66261,226 @@ class TranscriptionSessions extends APIResource { return this._client.post('/realtime/transcription_sessions', { body, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), }); } -} -//# sourceMappingURL=transcription-sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs +} +//# sourceMappingURL=transcription-sessions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Realtime extends APIResource { + constructor() { + super(...arguments); + this.sessions = new Sessions(this._client); + this.transcriptionSessions = new TranscriptionSessions(this._client); + } +} +Realtime.Sessions = Sessions; +Realtime.TranscriptionSessions = TranscriptionSessions; +//# sourceMappingURL=realtime.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class messages_Messages extends APIResource { + /** + * Create a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(threadID, body, options) { + return this._client.post(path `/threads/${threadID}/messages`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieve a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(messageID, params, options) { + const { thread_id } = params; + return this._client.get(path `/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(messageID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path `/threads/${thread_id}/messages/${messageID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of messages for a given thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path `/threads/${threadID}/messages`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Deletes a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(messageID, params, options) { + const { thread_id } = params; + return this._client.delete(path `/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Steps extends APIResource { + /** + * Retrieves a run step. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(stepID, params, options) { + const { thread_id, run_id, ...query } = params; + return this._client.get(path `/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of run steps belonging to a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(runID, params, options) { + const { thread_id, ...query } = params; + return this._client.getAPIList(path `/threads/${thread_id}/runs/${runID}/steps`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=steps.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/base64.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +const toBase64 = (data) => { + if (!data) + return ''; + if (typeof globalThis.Buffer !== 'undefined') { + return globalThis.Buffer.from(data).toString('base64'); + } + if (typeof data === 'string') { + data = encodeUTF8(data); + } + if (typeof btoa !== 'undefined') { + return btoa(String.fromCharCode.apply(null, data)); + } + throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); +}; +const fromBase64 = (str) => { + if (typeof globalThis.Buffer !== 'undefined') { + const buf = globalThis.Buffer.from(str, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + if (typeof atob !== 'undefined') { + const bstr = atob(str); + const buf = new Uint8Array(bstr.length); + for (let i = 0; i < bstr.length; i++) { + buf[i] = bstr.charCodeAt(i); + } + return buf; + } + throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); +}; +/** + * Converts a Base64 encoded string to a Float32Array. + * @param base64Str - The Base64 encoded string. + * @returns An Array of numbers interpreted as Float32 values. + */ +const toFloat32Array = (base64Str) => { + if (typeof Buffer !== 'undefined') { + // for Node.js environment + const buf = Buffer.from(base64Str, 'base64'); + return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); + } + else { + // for legacy web platform APIs + const binaryStr = atob(base64Str); + const len = binaryStr.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryStr.charCodeAt(i); + } + return Array.from(new Float32Array(bytes.buffer)); + } +}; +//# sourceMappingURL=base64.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/env.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Realtime extends APIResource { - constructor() { - super(...arguments); - this.sessions = new Sessions(this._client); - this.transcriptionSessions = new TranscriptionSessions(this._client); - } -} -Realtime.Sessions = Sessions; -Realtime.TranscriptionSessions = TranscriptionSessions; -//# sourceMappingURL=realtime.mjs.map + +//# sourceMappingURL=utils.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/AssistantStream.mjs -var AssistantStream_classPrivateFieldGet = (undefined && undefined.__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 AssistantStream_classPrivateFieldSet = (undefined && undefined.__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 _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; +var _AssistantStream_instances, _a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; + @@ -74105,7 +66559,7 @@ class AssistantStream extends EventStream { }; } static fromReadableStream(stream) { - const runner = new AssistantStream(); + const runner = new _a(); runner._run(() => runner._fromReadableStream(stream)); return runner; } @@ -74119,26 +66573,26 @@ class AssistantStream extends EventStream { this._connected(); const stream = Stream.fromReadableStream(readableStream, this.controller); for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } toReadableStream() { const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); return stream.toReadableStream(); } - static createToolAssistantStream(threadId, runId, runs, params, options) { - const runner = new AssistantStream(); - runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, params, { + static createToolAssistantStream(runId, runs, params, options) { + const runner = new _a(); + runner._run(() => runner._runToolAssistantStream(runId, runs, params, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, })); return runner; } - async _createToolAssistantStream(run, threadId, runId, params, options) { + async _createToolAssistantStream(run, runId, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) @@ -74146,21 +66600,21 @@ class AssistantStream extends EventStream { signal.addEventListener('abort', () => this.controller.abort()); } const body = { ...params, stream: true }; - const stream = await run.submitToolOutputs(threadId, runId, body, { + const stream = await run.submitToolOutputs(runId, body, { ...options, signal: this.controller.signal, }); this._connected(); for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } static createThreadAssistantStream(params, thread, options) { - const runner = new AssistantStream(); + const runner = new _a(); runner._run(() => runner._threadAssistantStream(params, thread, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, @@ -74168,7 +66622,7 @@ class AssistantStream extends EventStream { return runner; } static createAssistantStream(threadId, runs, params, options) { - const runner = new AssistantStream(); + const runner = new _a(); runner._run(() => runner._runAssistantStream(threadId, runs, params, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, @@ -74176,30 +66630,30 @@ class AssistantStream extends EventStream { return runner; } currentEvent() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); + return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); } currentRun() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); + return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); } currentMessageSnapshot() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); + return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); } currentRunStepSnapshot() { - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); + return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); } async finalRunSteps() { await this.done(); - return Object.values(AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); } async finalMessages() { await this.done(); - return Object.values(AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); } async finalRun() { await this.done(); - if (!AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) throw Error('Final run was not received.'); - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); } async _createThreadAssistantStream(thread, params, options) { const signal = options?.signal; @@ -74212,12 +66666,12 @@ class AssistantStream extends EventStream { const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } async _createAssistantStream(run, threadId, params, options) { const signal = options?.signal; @@ -74230,12 +66684,12 @@ class AssistantStream extends EventStream { const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); this._connected(); for await (const event of stream) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return this._addRun(AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); } static accumulateDelta(acc, delta) { for (const [key, deltaValue] of Object.entries(delta)) { @@ -74306,15 +66760,15 @@ class AssistantStream extends EventStream { async _runAssistantStream(threadId, runs, params, options) { return await this._createAssistantStream(runs, threadId, params, options); } - async _runToolAssistantStream(threadId, runId, runs, params, options) { - return await this._createToolAssistantStream(runs, threadId, runId, params, options); + async _runToolAssistantStream(runId, runs, params, options) { + return await this._createToolAssistantStream(runs, runId, params, options); } } -_AssistantStream_addEvent = function _AssistantStream_addEvent(event) { +_a = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { if (this.ended) return; - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); switch (event.event) { case 'thread.created': //No action on this event. @@ -74329,7 +66783,7 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { case 'thread.run.cancelling': case 'thread.run.cancelled': case 'thread.run.expired': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); break; case 'thread.run.step.created': case 'thread.run.step.in_progress': @@ -74338,14 +66792,14 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { case 'thread.run.step.failed': case 'thread.run.step.cancelled': case 'thread.run.step.expired': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); break; case 'thread.message.created': case 'thread.message.in_progress': case 'thread.message.delta': case 'thread.message.completed': case 'thread.message.incomplete': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); break; case 'error': //This is included for completeness, but errors are processed in the SSE event processing so this should not occur @@ -74357,13 +66811,13 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { if (this.ended) { throw new error_OpenAIError(`stream has ended, this shouldn't happen`); } - if (!AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) throw Error('Final run has not been received'); - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { - const [accumulatedMessage, newContent] = AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); - AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; + const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; for (const content of newContent) { const snapshotContent = accumulatedMessage.content[content.index]; if (snapshotContent?.type == 'text') { @@ -74391,48 +66845,48 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { throw Error('The snapshot associated with this text delta is not text or missing'); } } - if (content.index != AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { + if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { //See if we have in progress content - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { - switch (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { + if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { + switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { case 'text': - this._emit('textDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); break; case 'image_file': - this._emit('imageFileDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); break; } } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); + __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); } } break; case 'thread.message.completed': case 'thread.message.incomplete': //We emit the latest content we were working on on completion (including incomplete) - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { - const currentContent = event.data.content[AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; + if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { + const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; if (currentContent) { switch (currentContent.type) { case 'image_file': - this._emit('imageFileDone', currentContent.image_file, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); break; case 'text': - this._emit('textDone', currentContent.text, AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); break; } } } - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { + if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { this._emit('messageDone', event.data); } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); + __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); } }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { - const accumulatedRunStep = AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); switch (event.event) { case 'thread.run.step.created': this._emit('runStepCreated', event.data); @@ -74444,17 +66898,17 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { delta.step_details.tool_calls && accumulatedRunStep.step_details.type == 'tool_calls') { for (const toolCall of delta.step_details.tool_calls) { - if (toolCall.index == AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { + if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); } else { - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); } - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) - this._emit('toolCallCreated', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) + this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); } } } @@ -74464,12 +66918,12 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { case 'thread.run.step.failed': case 'thread.run.step.cancelled': case 'thread.run.step.expired': - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); + __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); const details = event.data.step_details; if (details.type == 'tool_calls') { - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); } } this._emit('runStepDone', event.data, accumulatedRunStep); @@ -74478,34 +66932,34 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { break; } }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { - AssistantStream_classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); + __classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); this._emit('event', event); }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { switch (event.event) { case 'thread.run.step.created': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; return event.data; case 'thread.run.step.delta': - let snapshot = AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; if (!snapshot) { throw Error('Received a RunStepDelta before creation of a snapshot'); } let data = event.data; if (data.delta) { - const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta); - AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + const accumulated = _a.accumulateDelta(snapshot, data.delta); + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; } - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; case 'thread.run.step.completed': case 'thread.run.step.failed': case 'thread.run.step.cancelled': case 'thread.run.step.expired': case 'thread.run.step.in_progress': - AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; break; } - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) - return AssistantStream_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) + return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; throw new Error('No snapshot available'); }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { let newContent = []; @@ -74523,7 +66977,7 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { for (const contentElement of data.delta.content) { if (contentElement.index in snapshot.content) { let currentContent = snapshot.content[contentElement.index]; - snapshot.content[contentElement.index] = AssistantStream_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); + snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); } else { snapshot.content[contentElement.index] = contentElement; @@ -74544,449 +66998,1004 @@ _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { throw Error('Received thread message event with no existing snapshot'); } } - throw Error('Tried to accumulate a non-message event'); -}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { - return AssistantStream.accumulateDelta(currentContent, contentElement); -}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); - switch (event.event) { - case 'thread.run.created': - break; - case 'thread.run.queued': - break; - case 'thread.run.in_progress': - break; - case 'thread.run.requires_action': - case 'thread.run.cancelled': - case 'thread.run.failed': - case 'thread.run.completed': - case 'thread.run.expired': - AssistantStream_classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); - if (AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', AssistantStream_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - AssistantStream_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } - break; - case 'thread.run.cancelling': - break; + throw Error('Tried to accumulate a non-message event'); +}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { + return _a.accumulateDelta(currentContent, contentElement); +}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { + __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + case 'thread.run.incomplete': + __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); + if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + break; + case 'thread.run.cancelling': + break; + } +}; +function AssistantStream_assertNever(_x) { } +//# sourceMappingURL=AssistantStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Runs extends APIResource { + constructor() { + super(...arguments); + this.steps = new Steps(this._client); + } + create(threadID, params, options) { + const { include, ...body } = params; + return this._client.post(path `/threads/${threadID}/runs`, { + query: { include }, + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }); + } + /** + * Retrieves a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(runID, params, options) { + const { thread_id } = params; + return this._client.get(path `/threads/${thread_id}/runs/${runID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path `/threads/${thread_id}/runs/${runID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of runs belonging to a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path `/threads/${threadID}/runs`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Cancels a run that is `in_progress`. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + cancel(runID, params, options) { + const { thread_id } = params; + return this._client.post(path `/threads/${thread_id}/runs/${runID}/cancel`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(run.id, { thread_id: threadId }, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(runId, params, options) { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const { data: run, response } = await this.retrieve(runId, params, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'incomplete': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path `/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(runId, params, options) { + const run = await this.submitToolOutputs(runId, params, options); + return await this.poll(run.id, params, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(runId, params, options) { + return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); + } +} +Runs.Steps = Steps; +//# sourceMappingURL=runs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Threads extends APIResource { + constructor() { + super(...arguments); + this.runs = new Runs(this._client); + this.messages = new messages_Messages(this._client); + } + /** + * Create a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(body = {}, options) { + return this._client.post('/threads', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(threadID, options) { + return this._client.get(path `/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(threadID, body, options) { + return this._client.post(path `/threads/${threadID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(threadID, options) { + return this._client.delete(path `/threads/${threadID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + createAndRun(body, options) { + return this._client.post('/threads/runs', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: body.stream ?? false, + }); + } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} +Threads.Runs = Runs; +Threads.Messages = messages_Messages; +//# sourceMappingURL=threads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Beta extends APIResource { + constructor() { + super(...arguments); + this.realtime = new Realtime(this._client); + this.assistants = new Assistants(this._client); + this.threads = new Threads(this._client); + } +} +Beta.Realtime = Realtime; +Beta.Assistants = Assistants; +Beta.Threads = Threads; +//# sourceMappingURL=beta.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class completions_Completions extends APIResource { + create(body, options) { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); + } +} +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/content.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Content extends APIResource { + /** + * Retrieve Container File Content + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path `/containers/${container_id}/files/${fileID}/content`, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } +} +//# sourceMappingURL=content.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Files extends APIResource { + constructor() { + super(...arguments); + this.content = new Content(this._client); + } + /** + * Create a Container File + * + * You can send either a multipart/form-data request with the raw file content, or + * a JSON request with a file ID. + */ + create(containerID, body, options) { + return this._client.post(path `/containers/${containerID}/files`, multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Retrieve Container File + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path `/containers/${container_id}/files/${fileID}`, options); + } + /** + * List Container files + */ + list(containerID, query = {}, options) { + return this._client.getAPIList(path `/containers/${containerID}/files`, (CursorPage), { + query, + ...options, + }); + } + /** + * Delete Container File + */ + delete(fileID, params, options) { + const { container_id } = params; + return this._client.delete(path `/containers/${container_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +Files.Content = Content; +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/containers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class Containers extends APIResource { + constructor() { + super(...arguments); + this.files = new Files(this._client); + } + /** + * Create Container + */ + create(body, options) { + return this._client.post('/containers', { body, ...options }); + } + /** + * Retrieve Container + */ + retrieve(containerID, options) { + return this._client.get(path `/containers/${containerID}`, options); + } + /** + * List Containers + */ + list(query = {}, options) { + return this._client.getAPIList('/containers', (CursorPage), { query, ...options }); + } + /** + * Delete Container + */ + delete(containerID, options) { + return this._client.delete(path `/containers/${containerID}`, { + ...options, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +Containers.Files = Files; +//# sourceMappingURL=containers.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Embeddings extends APIResource { + /** + * Creates an embedding vector representing the input text. + * + * @example + * ```ts + * const createEmbeddingResponse = + * await client.embeddings.create({ + * input: 'The quick brown fox jumped over the lazy dog', + * model: 'text-embedding-3-small', + * }); + * ``` + */ + create(body, options) { + const hasUserProvidedEncodingFormat = !!body.encoding_format; + // No encoding_format specified, defaulting to base64 for performance reasons + // See https://github.com/openai/openai-node/pull/1312 + let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; + if (hasUserProvidedEncodingFormat) { + loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format); + } + const response = this._client.post('/embeddings', { + body: { + ...body, + encoding_format: encoding_format, + }, + ...options, + }); + // if the user specified an encoding_format, return the response as-is + if (hasUserProvidedEncodingFormat) { + return response; + } + // in this stage, we are sure the user did not specify an encoding_format + // and we defaulted to base64 for performance reasons + // we are sure then that the response is base64 encoded, let's decode it + // the returned result will be a float32 array since this is OpenAI API's default encoding + loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64'); + return response._thenUnwrap((response) => { + if (response && response.data) { + response.data.forEach((embeddingBase64Obj) => { + const embeddingBase64Str = embeddingBase64Obj.embedding; + embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); + }); + } + return response; + }); + } +} +//# sourceMappingURL=embeddings.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class OutputItems extends APIResource { + /** + * Get an evaluation run output item by ID. + */ + retrieve(outputItemID, params, options) { + const { eval_id, run_id } = params; + return this._client.get(path `/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); + } + /** + * Get a list of output items for an evaluation run. + */ + list(runID, params, options) { + const { eval_id, ...query } = params; + return this._client.getAPIList(path `/evals/${eval_id}/runs/${runID}/output_items`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=output-items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class runs_Runs extends APIResource { + constructor() { + super(...arguments); + this.outputItems = new OutputItems(this._client); + } + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what + * model configuration to use to test. The datasource will be validated against the + * schema specified in the config of the evaluation. + */ + create(evalID, body, options) { + return this._client.post(path `/evals/${evalID}/runs`, { body, ...options }); + } + /** + * Get an evaluation run by ID. + */ + retrieve(runID, params, options) { + const { eval_id } = params; + return this._client.get(path `/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Get a list of runs for an evaluation. + */ + list(evalID, query = {}, options) { + return this._client.getAPIList(path `/evals/${evalID}/runs`, (CursorPage), { + query, + ...options, + }); + } + /** + * Delete an eval run. + */ + delete(runID, params, options) { + const { eval_id } = params; + return this._client.delete(path `/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Cancel an ongoing evaluation run. + */ + cancel(runID, params, options) { + const { eval_id } = params; + return this._client.post(path `/evals/${eval_id}/runs/${runID}`, options); + } +} +runs_Runs.OutputItems = OutputItems; +//# sourceMappingURL=runs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Evals extends APIResource { + constructor() { + super(...arguments); + this.runs = new runs_Runs(this._client); + } + /** + * Create the structure of an evaluation that can be used to test a model's + * performance. An evaluation is a set of testing criteria and the config for a + * data source, which dictates the schema of the data used in the evaluation. After + * creating an evaluation, you can run it on different models and model parameters. + * We support several types of graders and datasources. For more information, see + * the [Evals guide](https://platform.openai.com/docs/guides/evals). + */ + create(body, options) { + return this._client.post('/evals', { body, ...options }); + } + /** + * Get an evaluation by ID. + */ + retrieve(evalID, options) { + return this._client.get(path `/evals/${evalID}`, options); } -}; -function AssistantStream_assertNever(_x) { } -//# sourceMappingURL=AssistantStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs + /** + * Update certain properties of an evaluation. + */ + update(evalID, body, options) { + return this._client.post(path `/evals/${evalID}`, { body, ...options }); + } + /** + * List evaluations for a project. + */ + list(query = {}, options) { + return this._client.getAPIList('/evals', (CursorPage), { query, ...options }); + } + /** + * Delete an evaluation. + */ + delete(evalID, options) { + return this._client.delete(path `/evals/${evalID}`, options); + } +} +Evals.Runs = runs_Runs; +//# sourceMappingURL=evals.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class messages_Messages extends APIResource { + + + + +class files_Files extends APIResource { /** - * Create a message. + * Upload a file that can be used across various endpoints. Individual files can be + * up to 512 MB, and the size of all files uploaded by one organization can be up + * to 100 GB. * - * @example - * ```ts - * const message = await client.beta.threads.messages.create( - * 'thread_id', - * { content: 'string', role: 'user' }, - * ); - * ``` + * The Assistants API supports files up to 2 million tokens and of specific file + * types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for + * details. + * + * The Fine-tuning API only supports `.jsonl` files. The input also has certain + * required formats for fine-tuning + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * + * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also + * has a specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. */ - create(threadId, body, options) { - return this._client.post(`/threads/${threadId}/messages`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + create(body, options) { + return this._client.post('/files', multipartFormRequestOptions({ body, ...options }, this._client)); } /** - * Retrieve a message. - * - * @example - * ```ts - * const message = await client.beta.threads.messages.retrieve( - * 'thread_id', - * 'message_id', - * ); - * ``` + * Returns information about a specific file. + */ + retrieve(fileID, options) { + return this._client.get(path `/files/${fileID}`, options); + } + /** + * Returns a list of files. + */ + list(query = {}, options) { + return this._client.getAPIList('/files', (CursorPage), { query, ...options }); + } + /** + * Delete a file. + */ + delete(fileID, options) { + return this._client.delete(path `/files/${fileID}`, options); + } + /** + * Returns the contents of the specified file. */ - retrieve(threadId, messageId, options) { - return this._client.get(`/threads/${threadId}/messages/${messageId}`, { + content(fileID, options) { + return this._client.get(path `/files/${fileID}/content`, { ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, }); } /** - * Modifies a message. + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); + } + } + return file; + } +} +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Methods extends APIResource { +} +//# sourceMappingURL=methods.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Graders extends APIResource { + /** + * Run a grader. * * @example * ```ts - * const message = await client.beta.threads.messages.update( - * 'thread_id', - * 'message_id', - * ); + * const response = await client.fineTuning.alpha.graders.run({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * model_sample: 'model_sample', + * }); * ``` */ - update(threadId, messageId, body, options) { - return this._client.post(`/threads/${threadId}/messages/${messageId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - list(threadId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(threadId, {}, query); - } - return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + run(body, options) { + return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); } /** - * Deletes a message. + * Validate a grader. * * @example * ```ts - * const messageDeleted = - * await client.beta.threads.messages.del( - * 'thread_id', - * 'message_id', - * ); + * const response = + * await client.fineTuning.alpha.graders.validate({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * }); * ``` */ - del(threadId, messageId, options) { - return this._client.delete(`/threads/${threadId}/messages/${messageId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + validate(body, options) { + return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); } } -class MessagesPage extends CursorPage { -} -messages_Messages.MessagesPage = MessagesPage; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs +//# sourceMappingURL=graders.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Steps extends APIResource { - retrieve(threadId, runId, stepId, query = {}, options) { - if (isRequestOptions(query)) { - return this.retrieve(threadId, runId, stepId, {}, query); - } - return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - list(threadId, runId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(threadId, runId, {}, query); - } - return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { - query, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); +class Alpha extends APIResource { + constructor() { + super(...arguments); + this.graders = new Graders(this._client); } } -class RunStepsPage extends CursorPage { -} -Steps.RunStepsPage = RunStepsPage; -//# sourceMappingURL=steps.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs +Alpha.Graders = Graders; +//# sourceMappingURL=alpha.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Runs extends APIResource { - constructor() { - super(...arguments); - this.steps = new Steps(this._client); - } - create(threadId, params, options) { - const { include, ...body } = params; - return this._client.post(`/threads/${threadId}/runs`, { - query: { include }, - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - stream: params.stream ?? false, - }); - } +class Permissions extends APIResource { /** - * Retrieves a run. + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. * * @example * ```ts - * const run = await client.beta.threads.runs.retrieve( - * 'thread_id', - * 'run_id', - * ); + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } * ``` */ - retrieve(threadId, runId, options) { - return this._client.get(`/threads/${threadId}/runs/${runId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (Page), { body, method: 'post', ...options }); } /** - * Modifies a run. + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. * * @example * ```ts - * const run = await client.beta.threads.runs.update( - * 'thread_id', - * 'run_id', - * ); + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); * ``` */ - update(threadId, runId, body, options) { - return this._client.post(`/threads/${threadId}/runs/${runId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); - } - list(threadId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(threadId, {}, query); - } - return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get(path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { query, ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, }); } /** - * Cancels a run that is `in_progress`. + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. * * @example * ```ts - * const run = await client.beta.threads.runs.cancel( - * 'thread_id', - * 'run_id', - * ); + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); * ``` */ - cancel(threadId, runId, options) { - return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete(path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); } - /** - * A helper to create a run an poll for a terminal state. More information on Run - * lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async createAndPoll(threadId, body, options) { - const run = await this.create(threadId, body, options); - return await this.poll(threadId, run.id, options); +} +//# sourceMappingURL=permissions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Checkpoints extends APIResource { + constructor() { + super(...arguments); + this.permissions = new Permissions(this._client); } +} +Checkpoints.Permissions = Permissions; +//# sourceMappingURL=checkpoints.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class checkpoints_Checkpoints extends APIResource { /** - * Create a Run stream + * List checkpoints for a fine-tuning job. * - * @deprecated use `stream` instead - */ - createAndStream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); - } - /** - * A helper to poll a run status until it reaches a terminal state. More - * information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async poll(threadId, runId, options) { - const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' }; - if (options?.pollIntervalMs) { - headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString(); - } - while (true) { - const { data: run, response } = await this.retrieve(threadId, runId, { - ...options, - headers: { ...options?.headers, ...headers }, - }).withResponse(); - switch (run.status) { - //If we are in any sort of intermediate state we poll - case 'queued': - case 'in_progress': - case 'cancelling': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep(sleepInterval); - break; - //We return the run in any terminal state. - case 'requires_action': - case 'incomplete': - case 'cancelled': - case 'completed': - case 'failed': - case 'expired': - return run; - } - } - } - /** - * Create a Run stream - */ - stream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); - } - submitToolOutputs(threadId, runId, body, options) { - return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - stream: body.stream ?? false, - }); - } - /** - * A helper to submit a tool output to a run and poll for a terminal run state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async submitToolOutputsAndPoll(threadId, runId, body, options) { - const run = await this.submitToolOutputs(threadId, runId, body, options); - return await this.poll(threadId, run.id, options); - } - /** - * Submit the tool outputs from a previous run and stream the run to a terminal - * state. More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` */ - submitToolOutputsStream(threadId, runId, body, options) { - return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options); + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options }); } } -class RunsPage extends CursorPage { -} -Runs.RunsPage = RunsPage; -Runs.Steps = Steps; -Runs.RunStepsPage = RunStepsPage; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs +//# sourceMappingURL=checkpoints.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Threads extends APIResource { +class Jobs extends APIResource { constructor() { super(...arguments); - this.runs = new Runs(this._client); - this.messages = new messages_Messages(this._client); + this.checkpoints = new checkpoints_Checkpoints(this._client); } - create(body = {}, options) { - if (isRequestOptions(body)) { - return this.create({}, body); - } - return this._client.post('/threads', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); } /** - * Retrieves a thread. + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) * * @example * ```ts - * const thread = await client.beta.threads.retrieve( - * 'thread_id', + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', * ); * ``` */ - retrieve(threadId, options) { - return this._client.get(`/threads/${threadId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + retrieve(fineTuningJobID, options) { + return this._client.get(path `/fine_tuning/jobs/${fineTuningJobID}`, options); } /** - * Modifies a thread. + * List your organization's fine-tuning jobs * * @example * ```ts - * const thread = await client.beta.threads.update( - * 'thread_id', - * ); + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } * ``` */ - update(threadId, body, options) { - return this._client.post(`/threads/${threadId}`, { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + list(query = {}, options) { + return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options }); } /** - * Delete a thread. + * Immediately cancel a fine-tune job. * * @example * ```ts - * const threadDeleted = await client.beta.threads.del( - * 'thread_id', + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', * ); * ``` */ - del(threadId, options) { - return this._client.delete(`/threads/${threadId}`, { - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - }); + cancel(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); } - createAndRun(body, options) { - return this._client.post('/threads/runs', { - body, - ...options, - headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers }, - stream: body.stream ?? false, - }); + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options }); } /** - * A helper to create a thread, start a run and then poll for a terminal state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` */ - async createAndRunPoll(body, options) { - const run = await this.createAndRun(body, options); - return await this.runs.poll(run.thread_id, run.id, options); + pause(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); } /** - * Create a thread and stream the run back + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` */ - createAndRunStream(body, options) { - return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + resume(fineTuningJobID, options) { + return this._client.post(path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); } } -Threads.Runs = Runs; -Threads.RunsPage = RunsPage; -Threads.Messages = messages_Messages; -Threads.MessagesPage = MessagesPage; -//# sourceMappingURL=threads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs +Jobs.Checkpoints = checkpoints_Checkpoints; +//# sourceMappingURL=jobs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -74997,141 +68006,130 @@ Threads.MessagesPage = MessagesPage; -class Beta extends APIResource { +class FineTuning extends APIResource { constructor() { super(...arguments); - this.realtime = new Realtime(this._client); - this.chat = new chat_Chat(this._client); - this.assistants = new Assistants(this._client); - this.threads = new Threads(this._client); + this.methods = new Methods(this._client); + this.jobs = new Jobs(this._client); + this.checkpoints = new Checkpoints(this._client); + this.alpha = new Alpha(this._client); } } -Beta.Realtime = Realtime; -Beta.Assistants = Assistants; -Beta.AssistantsPage = AssistantsPage; -Beta.Threads = Threads; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs +FineTuning.Methods = Methods; +FineTuning.Jobs = Jobs; +FineTuning.Checkpoints = Checkpoints; +FineTuning.Alpha = Alpha; +//# sourceMappingURL=fine-tuning.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +class GraderModels extends APIResource { +} +//# sourceMappingURL=grader-models.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Batches extends APIResource { - /** - * Creates and executes a batch from an uploaded file of requests - */ - create(body, options) { - return this._client.post('/batches', { body, ...options }); - } - /** - * Retrieves a batch. - */ - retrieve(batchId, options) { - return this._client.get(`/batches/${batchId}`, options); - } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/batches', BatchesPage, { query, ...options }); - } - /** - * Cancels an in-progress batch. The batch will be in status `cancelling` for up to - * 10 minutes, before changing to `cancelled`, where it will have partial results - * (if any) available in the output file. - */ - cancel(batchId, options) { - return this._client.post(`/batches/${batchId}/cancel`, options); + +class graders_Graders extends APIResource { + constructor() { + super(...arguments); + this.graderModels = new GraderModels(this._client); } } -class BatchesPage extends CursorPage { -} -Batches.BatchesPage = BatchesPage; -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs +graders_Graders.GraderModels = GraderModels; +//# sourceMappingURL=graders.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Parts extends APIResource { +class Images extends APIResource { /** - * Adds a - * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. - * A Part represents a chunk of bytes from the file you are trying to upload. + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. * - * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload - * maximum of 8 GB. + * @example + * ```ts + * const imagesResponse = await client.images.createVariation({ + * image: fs.createReadStream('otter.png'), + * }); + * ``` + */ + createVariation(body, options) { + return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Creates an edited or extended image given one or more source images and a + * prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. * - * It is possible to add multiple Parts in parallel. You can decide the intended - * order of the Parts when you - * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + * @example + * ```ts + * const imagesResponse = await client.images.edit({ + * image: fs.createReadStream('path/to/file'), + * prompt: 'A cute baby sea otter wearing a beret', + * }); + * ``` + */ + edit(body, options) { + return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Creates an image given a prompt. + * [Learn more](https://platform.openai.com/docs/guides/images). + * + * @example + * ```ts + * const imagesResponse = await client.images.generate({ + * prompt: 'A cute baby sea otter', + * }); + * ``` */ - create(uploadId, body, options) { - return this._client.post(`/uploads/${uploadId}/parts`, multipartFormRequestOptions({ body, ...options })); + generate(body, options) { + return this._client.post('/images/generations', { body, ...options }); } } -//# sourceMappingURL=parts.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs +//# sourceMappingURL=images.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Uploads extends APIResource { - constructor() { - super(...arguments); - this.parts = new Parts(this._client); +class Models extends APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this._client.get(path `/models/${model}`, options); } /** - * Creates an intermediate - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object - * that you can add - * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. - * Currently, an Upload can accept at most 8 GB in total and expires after an hour - * after you create it. - * - * Once you complete the Upload, we will create a - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * contains all the parts you uploaded. This File is usable in the rest of our - * platform as a regular File object. - * - * For certain `purpose` values, the correct `mime_type` must be specified. Please - * refer to documentation for the - * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). - * - * For guidance on the proper filename extensions for each purpose, please follow - * the documentation on - * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. */ - create(body, options) { - return this._client.post('/uploads', { body, ...options }); + list(options) { + return this._client.getAPIList('/models', (Page), options); } /** - * Cancels the Upload. No Parts may be added after an Upload is cancelled. + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. */ - cancel(uploadId, options) { - return this._client.post(`/uploads/${uploadId}/cancel`, options); + delete(model, options) { + return this._client.delete(path `/models/${model}`, options); } +} +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Moderations extends APIResource { /** - * Completes the - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). - * - * Within the returned Upload object, there is a nested - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * is ready to use in the rest of the platform. - * - * You can specify the order of the Parts by passing in an ordered list of the Part - * IDs. - * - * The number of bytes uploaded upon completion must match the number of bytes - * initially specified when creating the Upload object. No Parts may be added after - * an Upload is completed. + * Classifies if text and/or image inputs are potentially harmful. Learn more in + * the [moderation guide](https://platform.openai.com/docs/guides/moderation). */ - complete(uploadId, body, options) { - return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options }); + create(body, options) { + return this._client.post('/moderations', { body, ...options }); } } -Uploads.Parts = Parts; -//# sourceMappingURL=uploads.mjs.map +//# sourceMappingURL=moderations.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/ResponsesParser.mjs @@ -75293,40 +68291,12 @@ function addOutputText(rsp) { rsp.output_text = texts.join(''); } //# sourceMappingURL=ResponsesParser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class InputItems extends APIResource { - list(responseId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(responseId, {}, query); - } - return this._client.getAPIList(`/responses/${responseId}/input_items`, ResponseItemsPage, { - query, - ...options, - }); - } -} - -//# sourceMappingURL=input-items.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/responses/ResponseStream.mjs -var ResponseStream_classPrivateFieldSet = (undefined && undefined.__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 ResponseStream_classPrivateFieldGet = (undefined && undefined.__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 _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse; + class ResponseStream extends EventStream { constructor(params) { super(); @@ -75334,43 +68304,56 @@ class ResponseStream extends EventStream { _ResponseStream_params.set(this, void 0); _ResponseStream_currentResponseSnapshot.set(this, void 0); _ResponseStream_finalResponse.set(this, void 0); - ResponseStream_classPrivateFieldSet(this, _ResponseStream_params, params, "f"); + __classPrivateFieldSet(this, _ResponseStream_params, params, "f"); } static createResponse(client, params, options) { const runner = new ResponseStream(params); - runner._run(() => runner._createResponse(client, params, { + runner._run(() => runner._createOrRetrieveResponse(client, params, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, })); return runner; } - async _createResponse(client, params, options) { + async _createOrRetrieveResponse(client, params, options) { const signal = options?.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener('abort', () => this.controller.abort()); } - ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); - const stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); + let stream; + let starting_after = null; + if ('response_id' in params) { + stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true }); + starting_after = params.starting_after ?? null; + } + else { + stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + } this._connected(); for await (const event of stream) { - ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event); + __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); } if (stream.controller.signal?.aborted) { throw new APIUserAbortError(); } - return ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); } [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { if (this.ended) return; - ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event) { + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); + }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) { if (this.ended) return; - const response = ResponseStream_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); - this._emit('event', event); + const maybeEmit = (name, event) => { + if (starting_after == null || event.sequence_number > starting_after) { + this._emit(name, event); + } + }; + const response = __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); + maybeEmit('event', event); switch (event.type) { case 'response.output_text.delta': { const output = response.output[event.output_index]; @@ -75385,7 +68368,7 @@ class ResponseStream extends EventStream { if (content.type !== 'output_text') { throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); } - this._emit('response.output_text.delta', { + maybeEmit('response.output_text.delta', { ...event, snapshot: content.text, }); @@ -75398,7 +68381,7 @@ class ResponseStream extends EventStream { throw new error_OpenAIError(`missing output at index ${event.output_index}`); } if (output.type === 'function_call') { - this._emit('response.function_call_arguments.delta', { + maybeEmit('response.function_call_arguments.delta', { ...event, snapshot: output.arguments, }); @@ -75406,29 +68389,28 @@ class ResponseStream extends EventStream { break; } default: - // @ts-ignore - this._emit(event.type, event); + maybeEmit(event.type, event); break; } }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { if (this.ended) { throw new error_OpenAIError(`stream has ended, this shouldn't happen`); } - const snapshot = ResponseStream_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); if (!snapshot) { throw new error_OpenAIError(`request ended without sending any events`); } - ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - const parsedResponse = finalizeResponse(snapshot, ResponseStream_classPrivateFieldGet(this, _ResponseStream_params, "f")); - ResponseStream_classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); + const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f")); + __classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); return parsedResponse; }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) { - let snapshot = ResponseStream_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + let snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); if (!snapshot) { if (event.type !== 'response.created') { throw new error_OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); } - snapshot = ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + snapshot = __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); return snapshot; } switch (event.type) { @@ -75474,7 +68456,7 @@ class ResponseStream extends EventStream { break; } case 'response.completed': { - ResponseStream_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + __classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); break; } } @@ -75536,7 +68518,7 @@ class ResponseStream extends EventStream { */ async finalResponse() { await this.done(); - const response = ResponseStream_classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); + const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); if (!response) throw new error_OpenAIError('stream ended without producing a ChatCompletion'); return response; @@ -75546,6 +68528,30 @@ function finalizeResponse(snapshot, params) { return maybeParseResponse(snapshot, params); } //# sourceMappingURL=ResponseStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class InputItems extends APIResource { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const responseItem of client.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list(responseID, query = {}, options) { + return this._client.getAPIList(path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=input-items.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/responses.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -75568,26 +68574,27 @@ class Responses extends APIResource { return rsp; }); } - retrieve(responseId, query = {}, options) { - if (isRequestOptions(query)) { - return this.retrieve(responseId, {}, query); - } - return this._client.get(`/responses/${responseId}`, { query, ...options }); + retrieve(responseID, query = {}, options) { + return this._client.get(path `/responses/${responseID}`, { + query, + ...options, + stream: query?.stream ?? false, + }); } /** * Deletes a model response with the given ID. * * @example * ```ts - * await client.responses.del( + * await client.responses.delete( * 'resp_677efb5139a88190b512bc3fef8e535d', * ); * ``` */ - del(responseId, options) { - return this._client.delete(`/responses/${responseId}`, { + delete(responseID, options) { + return this._client.delete(path `/responses/${responseID}`, { ...options, - headers: { Accept: '*/*', ...options?.headers }, + headers: buildHeaders([{ Accept: '*/*' }, options?.headers]), }); } parse(body, options) { @@ -75601,139 +68608,521 @@ class Responses extends APIResource { stream(body, options) { return ResponseStream.createResponse(this._client, body, options); } -} -class ResponseItemsPage extends CursorPage { + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const response = await client.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID, options) { + return this._client.post(path `/responses/${responseID}/cancel`, options); + } } Responses.InputItems = InputItems; //# sourceMappingURL=responses.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs +;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class OutputItems extends APIResource { +class Parts extends APIResource { /** - * Get an evaluation run output item by ID. + * Adds a + * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + * A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + * maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended + * order of the Parts when you + * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). */ - retrieve(evalId, runId, outputItemId, options) { - return this._client.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`, options); - } - list(evalId, runId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(evalId, runId, {}, query); - } - return this._client.getAPIList(`/evals/${evalId}/runs/${runId}/output_items`, OutputItemListResponsesPage, { query, ...options }); + create(uploadID, body, options) { + return this._client.post(path `/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options }, this._client)); } } -class OutputItemListResponsesPage extends CursorPage { -} -OutputItems.OutputItemListResponsesPage = OutputItemListResponsesPage; -//# sourceMappingURL=output-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs +//# sourceMappingURL=parts.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class runs_Runs extends APIResource { +class Uploads extends APIResource { constructor() { super(...arguments); - this.outputItems = new OutputItems(this._client); + this.parts = new Parts(this._client); + } + /** + * Creates an intermediate + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + * that you can add + * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an hour + * after you create it. + * + * Once you complete the Upload, we will create a + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * contains all the parts you uploaded. This File is usable in the rest of our + * platform as a regular File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. Please + * refer to documentation for the + * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please follow + * the documentation on + * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + */ + create(body, options) { + return this._client.post('/uploads', { body, ...options }); } /** - * Create a new evaluation run. This is the endpoint that will kick off grading. + * Cancels the Upload. No Parts may be added after an Upload is cancelled. */ - create(evalId, body, options) { - return this._client.post(`/evals/${evalId}/runs`, { body, ...options }); + cancel(uploadID, options) { + return this._client.post(path `/uploads/${uploadID}/cancel`, options); } /** - * Get an evaluation run by ID. + * Completes the + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part + * IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes + * initially specified when creating the Upload object. No Parts may be added after + * an Upload is completed. */ - retrieve(evalId, runId, options) { - return this._client.get(`/evals/${evalId}/runs/${runId}`, options); + complete(uploadID, body, options) { + return this._client.post(path `/uploads/${uploadID}/complete`, { body, ...options }); + } +} +Uploads.Parts = Parts; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs +/** + * Like `Promise.allSettled()` but throws an error if any promises are rejected. + */ +const allSettledWithThrow = async (promises) => { + const results = await Promise.allSettled(promises); + const rejected = results.filter((result) => result.status === 'rejected'); + if (rejected.length) { + for (const result of rejected) { + console.error(result.reason); + } + throw new Error(`${rejected.length} promise(s) failed - see the above errors`); } - list(evalId, query = {}, options) { - if (isRequestOptions(query)) { - return this.list(evalId, {}, query); + // Note: TS was complaining about using `.filter().map()` here for some reason + const values = []; + for (const result of results) { + if (result.status === 'fulfilled') { + values.push(result.value); } - return this._client.getAPIList(`/evals/${evalId}/runs`, RunListResponsesPage, { query, ...options }); } + return values; +}; +//# sourceMappingURL=Util.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class FileBatches extends APIResource { /** - * Delete an eval run. + * Create a vector store file batch. + */ + create(vectorStoreID, body, options) { + return this._client.post(path `/vector_stores/${vectorStoreID}/file_batches`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store file batch. + */ + retrieve(batchID, params, options) { + const { vector_store_id } = params; + return this._client.get(path `/vector_stores/${vector_store_id}/file_batches/${batchID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Cancel a vector store file batch. This attempts to cancel the processing of + * files in this batch as soon as possible. */ - del(evalId, runId, options) { - return this._client.delete(`/evals/${evalId}/runs/${runId}`, options); + cancel(batchID, params, options) { + const { vector_store_id } = params; + return this._client.post(path `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Cancel an ongoing evaluation run. + * Create a vector store batch and poll until all files have been processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const batch = await this.create(vectorStoreId, body); + return await this.poll(vectorStoreId, batch.id, options); + } + /** + * Returns a list of vector store files in a batch. + */ + listFiles(batchID, params, options) { + const { vector_store_id, ...query } = params; + return this._client.getAPIList(path `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (CursorPage), { query, ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); + } + /** + * Wait for the given file batch to be processed. + * + * Note: this will return even if one of the files failed to process, you need to + * check batch.file_counts.failed_count to handle this case. + */ + async poll(vectorStoreID, batchID, options) { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { + ...options, + headers, + }).withResponse(); + switch (batch.status) { + case 'in_progress': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + case 'failed': + case 'cancelled': + case 'completed': + return batch; + } + } + } + /** + * Uploads the given files concurrently and then creates a vector store file batch. + * + * The concurrency limit is configurable using the `maxConcurrency` parameter. */ - cancel(evalId, runId, options) { - return this._client.post(`/evals/${evalId}/runs/${runId}`, options); + async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { + if (files == null || files.length == 0) { + throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); + } + const configuredConcurrency = options?.maxConcurrency ?? 5; + // We cap the number of workers at the number of files (so we don't start any unnecessary workers) + const concurrencyLimit = Math.min(configuredConcurrency, files.length); + const client = this._client; + const fileIterator = files.values(); + const allFileIds = [...fileIds]; + // This code is based on this design. The libraries don't accommodate our environment limits. + // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all + async function processFiles(iterator) { + for (let item of iterator) { + const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); + allFileIds.push(fileObj.id); + } + } + // Start workers to process results + const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); + // Wait for all processing to complete. + await allSettledWithThrow(workers); + return await this.createAndPoll(vectorStoreId, { + file_ids: allFileIds, + }); } } -class RunListResponsesPage extends CursorPage { +//# sourceMappingURL=file-batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class vector_stores_files_Files extends APIResource { + /** + * Create a vector store file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). + */ + create(vectorStoreID, body, options) { + return this._client.post(path `/vector_stores/${vectorStoreID}/files`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store file. + */ + retrieve(fileID, params, options) { + const { vector_store_id } = params; + return this._client.get(path `/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Update attributes on a vector store file. + */ + update(fileID, params, options) { + const { vector_store_id, ...body } = params; + return this._client.post(path `/vector_stores/${vector_store_id}/files/${fileID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of vector store files. + */ + list(vectorStoreID, query = {}, options) { + return this._client.getAPIList(path `/vector_stores/${vectorStoreID}/files`, (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete a vector store file. This will remove the file from the vector store but + * the file itself will not be deleted. To delete the file, use the + * [delete file](https://platform.openai.com/docs/api-reference/files/delete) + * endpoint. + */ + delete(fileID, params, options) { + const { vector_store_id } = params; + return this._client.delete(path `/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Attach a file to the given vector store and wait for it to be processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const file = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file.id, options); + } + /** + * Wait for the vector store file to finish processing. + * + * Note: this will return even if the file failed to process, you need to check + * file.last_error and file.status to handle these cases + */ + async poll(vectorStoreID, fileID, options) { + const headers = buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const fileResponse = await this.retrieve(fileID, { + vector_store_id: vectorStoreID, + }, { ...options, headers }).withResponse(); + const file = fileResponse.data; + switch (file.status) { + case 'in_progress': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep(sleepInterval); + break; + case 'failed': + case 'completed': + return file; + } + } + } + /** + * Upload a file to the `files` API and then attach it to the given vector store. + * + * Note the file will be asynchronously processed (you can use the alternative + * polling helper method to wait for processing to complete). + */ + async upload(vectorStoreId, file, options) { + const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); + return this.create(vectorStoreId, { file_id: fileInfo.id }, options); + } + /** + * Add a file to a vector store and poll until processing is complete. + */ + async uploadAndPoll(vectorStoreId, file, options) { + const fileInfo = await this.upload(vectorStoreId, file, options); + return await this.poll(vectorStoreId, fileInfo.id, options); + } + /** + * Retrieve the parsed contents of a vector store file. + */ + content(fileID, params, options) { + const { vector_store_id } = params; + return this._client.getAPIList(path `/vector_stores/${vector_store_id}/files/${fileID}/content`, (Page), { ...options, headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); + } } -runs_Runs.RunListResponsesPage = RunListResponsesPage; -runs_Runs.OutputItems = OutputItems; -runs_Runs.OutputItemListResponsesPage = OutputItemListResponsesPage; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class Evals extends APIResource { + + + +class VectorStores extends APIResource { constructor() { super(...arguments); - this.runs = new runs_Runs(this._client); + this.files = new vector_stores_files_Files(this._client); + this.fileBatches = new FileBatches(this._client); + } + /** + * Create a vector store. + */ + create(body, options) { + return this._client.post('/vector_stores', { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store. + */ + retrieve(vectorStoreID, options) { + return this._client.get(path `/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Create the structure of an evaluation that can be used to test a model's - * performance. An evaluation is a set of testing criteria and a datasource. After - * creating an evaluation, you can run it on different models and model parameters. - * We support several types of graders and datasources. For more information, see - * the [Evals guide](https://platform.openai.com/docs/guides/evals). + * Modifies a vector store. */ - create(body, options) { - return this._client.post('/evals', { body, ...options }); + update(vectorStoreID, body, options) { + return this._client.post(path `/vector_stores/${vectorStoreID}`, { + body, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Get an evaluation by ID. + * Returns a list of vector stores. */ - retrieve(evalId, options) { - return this._client.get(`/evals/${evalId}`, options); + list(query = {}, options) { + return this._client.getAPIList('/vector_stores', (CursorPage), { + query, + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Update certain properties of an evaluation. + * Delete a vector store. */ - update(evalId, body, options) { - return this._client.post(`/evals/${evalId}`, { body, ...options }); - } - list(query = {}, options) { - if (isRequestOptions(query)) { - return this.list({}, query); - } - return this._client.getAPIList('/evals', EvalListResponsesPage, { query, ...options }); + delete(vectorStoreID, options) { + return this._client.delete(path `/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } /** - * Delete an evaluation. + * Search a vector store for relevant chunks based on a query and file attributes + * filter. */ - del(evalId, options) { - return this._client.delete(`/evals/${evalId}`, options); + search(vectorStoreID, body, options) { + return this._client.getAPIList(path `/vector_stores/${vectorStoreID}/search`, (Page), { + body, + method: 'post', + ...options, + headers: buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); } } -class EvalListResponsesPage extends CursorPage { -} -Evals.EvalListResponsesPage = EvalListResponsesPage; -Evals.Runs = runs_Runs; -Evals.RunListResponsesPage = RunListResponsesPage; -//# sourceMappingURL=evals.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/index.mjs +VectorStores.Files = vector_stores_files_Files; +VectorStores.FileBatches = FileBatches; +//# sourceMappingURL=vector-stores.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _a; + + + + + + + + + + + + + + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/client.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var client_a, _OpenAI_encoder; + + + + + + + + + + + + + + + @@ -75760,7 +69149,7 @@ var _a; /** * API Client for interfacing with the OpenAI API. */ -class OpenAI extends APIClient { +class OpenAI { /** * API Client for interfacing with the OpenAI API. * @@ -75769,38 +69158,19 @@ class OpenAI extends APIClient { * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_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 {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {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 {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) { - if (apiKey === undefined) { - throw new error_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, - project, - ...opts, - baseURL: baseURL || `https://api.openai.com/v1`, - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { - throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); - } - super({ - baseURL: options.baseURL, - timeout: options.timeout ?? 600000 /* 10 minutes */, - httpAgent: options.httpAgent, - maxRetries: options.maxRetries, - fetch: options.fetch, - }); - this.completions = new Completions(this); + _OpenAI_encoder.set(this, void 0); + this.completions = new completions_Completions(this); this.chat = new Chat(this); this.embeddings = new Embeddings(this); - this.files = new Files(this); + this.files = new files_Files(this); this.images = new Images(this); this.audio = new Audio(this); this.moderations = new Moderations(this); @@ -75813,31 +69183,408 @@ class OpenAI extends APIClient { this.uploads = new Uploads(this); this.responses = new Responses(this); this.evals = new Evals(this); + this.containers = new Containers(this); + if (apiKey === undefined) { + throw new error_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, + project, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? client_a.DEFAULT_TIMEOUT /* 10 minutes */; + this.logger = options.logger ?? console; + const defaultLogLevel = 'warn'; + // Set default logLevel early so that we can log a warning in parseLogLevel. + this.logLevel = defaultLogLevel; + this.logLevel = + parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + parseLogLevel(readEnv('OPENAI_LOG'), "process.env['OPENAI_LOG']", this) ?? + defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f"); this._options = options; this.apiKey = apiKey; this.organization = organization; this.project = project; } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + return new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + organization: this.organization, + project: this.project, + ...options, + }); + } defaultQuery() { return this._options.defaultQuery; } - defaultHeaders(opts) { - return { - ...super.defaultHeaders(opts), - 'OpenAI-Organization': this.organization, - 'OpenAI-Project': this.project, - ...this._options.defaultHeaders, - }; + validateHeaders({ values, nulls }) { + return; } authHeaders(opts) { - return { Authorization: `Bearer ${this.apiKey}` }; + return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); } stringifyQuery(query) { return stringify(query, { arrayFormat: 'brackets' }); } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path, query) { + 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(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => { + return { method, path, ...opts }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + await this.prepareRequest(req, { url, options }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); + const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + // detect native connection timeout errors + // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" + // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" + // others do not provide enough information to distinguish timeouts from other connection errors + const isTimeout = isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const specialHeaders = [...response.headers.entries()] + .filter(([name]) => name === 'x-request-id') + .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) + .join(''); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + // We don't need the body of this response. + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, undefined); + return new PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const fetchOptions = { + signal: controller.signal, + ...(isReadableBody ? { duplex: 'half' } : {}), + method: 'GET', + ...options, + }; + if (method) { + // Custom methods like 'patch' need to be uppercased + // See https://github.com/nodejs/undici/issues/2294 + fetchOptions.method = method.toUpperCase(); + } + try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + return await this.fetch.call(undefined, url, fetchOptions); + } + finally { + clearTimeout(timeout); + } + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.get('retry-after'); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query } = options; + const url = this.buildURL(path, query); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...(options.signal && { signal: options.signal }), + ...(globalThis.ReadableStream && + body instanceof globalThis.ReadableStream && { duplex: 'half' }), + ...(body && { body }), + ...(this.fetchOptions ?? {}), + ...(options.fetchOptions ?? {}), + }; + return { req, url, timeout: options.timeout }; + } + buildHeaders({ options, method, bodyHeaders, retryCount, }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...getPlatformHeaders(), + 'OpenAI-Organization': this.organization, + 'OpenAI-Project': this.project, + }, + this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers, + ]); + this.validateHeaders(headers); + return headers.values; + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || + body instanceof ArrayBuffer || + body instanceof DataView || + (typeof body === 'string' && + // Preserve legacy string encoding behavior for now + headers.values.has('content-type')) || + // `Blob` is superset of `File` + body instanceof Blob || + // `FormData` -> `multipart/form-data` + body instanceof FormData || + // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || + // Send chunked stream (each chunk has own `length`) + (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { + return { bodyHeaders: undefined, body: body }; + } + else if (typeof body === 'object' && + (Symbol.asyncIterator in body || + (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { + return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; + } + else { + return __classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }); + } + } } -_a = OpenAI; -OpenAI.OpenAI = _a; +client_a = OpenAI, _OpenAI_encoder = new WeakMap(); +OpenAI.OpenAI = client_a; OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes OpenAI.OpenAIError = error_OpenAIError; OpenAI.APIError = APIError; @@ -75853,30 +69600,29 @@ OpenAI.InternalServerError = InternalServerError; OpenAI.PermissionDeniedError = PermissionDeniedError; OpenAI.UnprocessableEntityError = UnprocessableEntityError; OpenAI.toFile = toFile; -OpenAI.fileFromPath = fileFromPath; -OpenAI.Completions = Completions; +OpenAI.Completions = completions_Completions; OpenAI.Chat = Chat; -OpenAI.ChatCompletionsPage = ChatCompletionsPage; OpenAI.Embeddings = Embeddings; -OpenAI.Files = Files; -OpenAI.FileObjectsPage = FileObjectsPage; +OpenAI.Files = files_Files; OpenAI.Images = Images; OpenAI.Audio = Audio; OpenAI.Moderations = Moderations; OpenAI.Models = Models; -OpenAI.ModelsPage = ModelsPage; OpenAI.FineTuning = FineTuning; OpenAI.Graders = graders_Graders; OpenAI.VectorStores = VectorStores; -OpenAI.VectorStoresPage = VectorStoresPage; -OpenAI.VectorStoreSearchResponsesPage = VectorStoreSearchResponsesPage; OpenAI.Beta = Beta; OpenAI.Batches = Batches; -OpenAI.BatchesPage = BatchesPage; OpenAI.Uploads = Uploads; OpenAI.Responses = Responses; OpenAI.Evals = Evals; -OpenAI.EvalListResponsesPage = EvalListResponsesPage; +OpenAI.Containers = Containers; +//# sourceMappingURL=client.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/azure.mjs + + + + /** API Client for interfacing with the Azure OpenAI API. */ class AzureOpenAI extends OpenAI { /** @@ -75890,10 +69636,10 @@ class AzureOpenAI extends OpenAI { * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {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 {Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('AZURE_OPENAI_API_KEY'), apiVersion = readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { @@ -75960,25 +69706,25 @@ class AzureOpenAI extends OpenAI { return undefined; } authHeaders(opts) { - return {}; + return; } async prepareOptions(opts) { + opts.headers = buildHeaders([opts.headers]); /** * The user should provide a bearer token provider if they want * to use Azure AD authentication. The user shouldn't set the * Authorization header manually because the header is overwritten * with the Azure AD token if a bearer token provider is provided. */ - if (opts.headers?.['api-key']) { + if (opts.headers.values.get('Authorization') || opts.headers.values.get('api-key')) { return super.prepareOptions(opts); } const token = await this._getAzureADToken(); - opts.headers ?? (opts.headers = {}); if (token) { - opts.headers['Authorization'] = `Bearer ${token}`; + opts.headers.values.set('Authorization', `Bearer ${token}`); } else if (this.apiKey !== API_KEY_SENTINEL) { - opts.headers['api-key'] = this.apiKey; + opts.headers.values.set('api-key', this.apiKey); } else { throw new error_OpenAIError('Unable to handle auth'); @@ -75994,11 +69740,20 @@ const _deployments_endpoints = new Set([ '/audio/translations', '/audio/speech', '/images/generations', + '/batches', + '/images/edits', ]); const API_KEY_SENTINEL = ''; +//# sourceMappingURL=azure.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + -/* harmony default export */ const openai = (OpenAI); //# sourceMappingURL=index.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/tslib.mjs function tslib_classPrivateFieldSet(receiver, state, value, kind, f) { @@ -76037,7 +69792,7 @@ let uuid_uuid4 = function () { //# sourceMappingURL=uuid.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/errors.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function isAbortError(err) { +function errors_isAbortError(err) { return (typeof err === 'object' && err !== null && // Spec-compliant fetch implementations @@ -76180,7 +69935,7 @@ const values_isAbsoluteURL = (url) => { return values_startsWithSchemeRegexp.test(url); }; /** Returns an object if the given value isn't an object, otherwise returns as-is */ -function maybeObj(x) { +function values_maybeObj(x) { if (typeof x !== 'object') { return {}; } @@ -76271,60 +70026,60 @@ const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/log.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const levelNumbers = { +const log_levelNumbers = { off: 0, error: 200, warn: 300, info: 400, debug: 500, }; -const parseLogLevel = (maybeLevel, sourceName, client) => { +const log_parseLogLevel = (maybeLevel, sourceName, client) => { if (!maybeLevel) { return undefined; } - if (values_hasOwn(levelNumbers, maybeLevel)) { + if (values_hasOwn(log_levelNumbers, maybeLevel)) { return maybeLevel; } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); return undefined; }; -function noop() { } -function makeLogFn(fnLevel, logger, logLevel) { - if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; +function log_noop() { } +function log_makeLogFn(fnLevel, logger, logLevel) { + if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { + return log_noop; } else { // Don't wrap logger functions, we want the stacktrace intact! return logger[fnLevel].bind(logger); } } -const noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop, +const log_noopLogger = { + error: log_noop, + warn: log_noop, + info: log_noop, + debug: log_noop, }; -let cachedLoggers = new WeakMap(); -function loggerFor(client) { +let log_cachedLoggers = new WeakMap(); +function log_loggerFor(client) { const logger = client.logger; const logLevel = client.logLevel ?? 'off'; if (!logger) { - return noopLogger; + return log_noopLogger; } - const cachedLogger = cachedLoggers.get(logger); + const cachedLogger = log_cachedLoggers.get(logger); if (cachedLogger && cachedLogger[0] === logLevel) { return cachedLogger[1]; } const levelLogger = { - error: makeLogFn('error', logger, logLevel), - warn: makeLogFn('warn', logger, logLevel), - info: makeLogFn('info', logger, logLevel), - debug: makeLogFn('debug', logger, logLevel), + error: log_makeLogFn('error', logger, logLevel), + warn: log_makeLogFn('warn', logger, logLevel), + info: log_makeLogFn('info', logger, logLevel), + debug: log_makeLogFn('debug', logger, logLevel), }; - cachedLoggers.set(logger, [logLevel, levelLogger]); + log_cachedLoggers.set(logger, [logLevel, levelLogger]); return levelLogger; } -const formatRequestDetails = (details) => { +const log_formatRequestDetails = (details) => { if (details.options) { details.options = { ...details.options }; delete details.options['headers']; // redundant + leaks internals @@ -76367,7 +70122,7 @@ const detect_platform_isRunningInBrowser = () => { /** * Note this does not detect 'browser'; for that, use getBrowserInfo(). */ -function getDetectedPlatform() { +function detect_platform_getDetectedPlatform() { if (typeof Deno !== 'undefined' && Deno.build != null) { return 'deno'; } @@ -76380,7 +70135,7 @@ function getDetectedPlatform() { return 'unknown'; } const detect_platform_getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); + const detectedPlatform = detect_platform_getDetectedPlatform(); if (detectedPlatform === 'deno') { return { 'X-Stainless-Lang': 'js', @@ -76512,13 +70267,13 @@ const detect_platform_getPlatformHeaders = () => { //# sourceMappingURL=detect-platform.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/shims.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function getDefaultFetch() { +function shims_getDefaultFetch() { if (typeof fetch !== 'undefined') { return fetch; } throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); } -function makeReadableStream(...args) { +function shims_makeReadableStream(...args) { const ReadableStream = globalThis.ReadableStream; if (typeof ReadableStream === 'undefined') { // Note: All of the platforms / runtimes we officially support already define @@ -76527,9 +70282,9 @@ function makeReadableStream(...args) { } return new ReadableStream(...args); } -function ReadableStreamFrom(iterable) { +function shims_ReadableStreamFrom(iterable) { let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ + return shims_makeReadableStream({ start() { }, async pull(controller) { const { done, value } = await iter.next(); @@ -76583,7 +70338,7 @@ function shims_ReadableStreamToAsyncIterable(stream) { * Cancels a ReadableStream we don't need to consume. * See https://undici.nodejs.org/#/?id=garbage-collection */ -async function CancelReadableStream(stream) { +async function shims_CancelReadableStream(stream) { if (stream === null || typeof stream !== 'object') return; if (stream[Symbol.asyncIterator]) { @@ -76598,7 +70353,7 @@ async function CancelReadableStream(stream) { //# sourceMappingURL=shims.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/request-options.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const FallbackEncoder = ({ headers, body }) => { +const request_options_FallbackEncoder = ({ headers, body }) => { return { bodyHeaders: { 'content-type': 'application/json', @@ -76608,7 +70363,7 @@ const FallbackEncoder = ({ headers, body }) => { }; //# sourceMappingURL=request-options.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs -function concatBytes(buffers) { +function bytes_concatBytes(buffers) { let length = 0; for (const buffer of buffers) { length += buffer.length; @@ -76621,21 +70376,21 @@ function concatBytes(buffers) { } return output; } -let encodeUTF8_; -function encodeUTF8(str) { +let bytes_encodeUTF8_; +function utils_bytes_encodeUTF8(str) { let encoder; - return (encodeUTF8_ ?? - ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); + return (bytes_encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (bytes_encodeUTF8_ = encoder.encode.bind(encoder))))(str); } -let decodeUTF8_; -function decodeUTF8(bytes) { +let bytes_decodeUTF8_; +function bytes_decodeUTF8(bytes) { let decoder; - return (decodeUTF8_ ?? - ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); + return (bytes_decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (bytes_decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); } //# sourceMappingURL=bytes.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs -var _LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; +var line_LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; /** @@ -76646,9 +70401,9 @@ var _LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; */ class line_LineDecoder { constructor() { - _LineDecoder_buffer.set(this, void 0); + line_LineDecoder_buffer.set(this, void 0); line_LineDecoder_carriageReturnIndex.set(this, void 0); - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, new Uint8Array(), "f"); tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); } decode(chunk) { @@ -76656,12 +70411,12 @@ class line_LineDecoder { return []; } const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? encodeUTF8(chunk) + : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) : chunk; - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, bytes_concatBytes([tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), binaryChunk]), "f"); const lines = []; let patternIndex; - while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { + while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { if (patternIndex.carriage && tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") == null) { // skip until we either get a corresponding `\n`, a new `\r` or nothing tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, patternIndex.index, "f"); @@ -76670,27 +70425,27 @@ class line_LineDecoder { // we got double \r or \rtext\n if (tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(decodeUTF8(tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); + lines.push(bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); continue; } const endIndex = tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = decodeUTF8(tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + const line = bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, endIndex)); lines.push(line); - tslib_classPrivateFieldSet(this, _LineDecoder_buffer, tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); } return lines; } flush() { - if (!tslib_classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { + if (!tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").length) { return []; } return this.decode('\n'); } } -_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); +line_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); // prettier-ignore line_LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); line_LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; @@ -76803,7 +70558,7 @@ class streaming_Stream { } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) + if (errors_isAbortError(e)) return; throw e; } @@ -76850,7 +70605,7 @@ class streaming_Stream { } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) + if (errors_isAbortError(e)) return; throw e; } @@ -76898,7 +70653,7 @@ class streaming_Stream { toReadableStream() { const self = this; let iter; - return makeReadableStream({ + return shims_makeReadableStream({ async start() { iter = self[Symbol.asyncIterator](); }, @@ -76907,7 +70662,7 @@ class streaming_Stream { const { value, done } = await iter.next(); if (done) return ctrl.close(); - const bytes = encodeUTF8(JSON.stringify(value) + '\n'); + const bytes = utils_bytes_encodeUTF8(JSON.stringify(value) + '\n'); ctrl.enqueue(bytes); } catch (err) { @@ -76956,7 +70711,7 @@ async function* streaming_iterSSEChunks(iterator) { continue; } const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? encodeUTF8(chunk) + : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) : chunk; let newData = new Uint8Array(data.length + binaryChunk.length); newData.set(data); @@ -77029,7 +70784,7 @@ async function parse_defaultParseResponse(client, props) { const { response, requestLogID, retryOfRequestLogID, startTime } = props; const body = await (async () => { if (props.options.stream) { - loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + log_loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); // Note: there is an invariant here that isn't represented in the type system // that if you set `stream: true` the response type must also be `Stream` if (props.options.__streamClass) { @@ -77049,12 +70804,12 @@ async function parse_defaultParseResponse(client, props) { const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); if (isJSON) { const json = await response.json(); - return addRequestID(json, response); + return parse_addRequestID(json, response); } const text = await response.text(); return text; })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + log_loggerFor(client).debug(`[${requestLogID}] response parsed`, log_formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, @@ -77063,7 +70818,7 @@ async function parse_defaultParseResponse(client, props) { })); return body; } -function addRequestID(value, response) { +function parse_addRequestID(value, response) { if (!value || typeof value !== 'object' || Array.isArray(value)) { return value; } @@ -77075,7 +70830,7 @@ function addRequestID(value, response) { //# sourceMappingURL=parse.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/api-promise.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _APIPromise_client; +var api_promise_APIPromise_client; /** @@ -77092,11 +70847,11 @@ class api_promise_APIPromise extends Promise { }); this.responsePromise = responsePromise; this.parseResponse = parseResponse; - _APIPromise_client.set(this, void 0); - tslib_classPrivateFieldSet(this, _APIPromise_client, client, "f"); + api_promise_APIPromise_client.set(this, void 0); + tslib_classPrivateFieldSet(this, api_promise_APIPromise_client, client, "f"); } _thenUnwrap(transform) { - return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), this.responsePromise, async (client, props) => parse_addRequestID(transform(await this.parseResponse(client, props), props), props.response)); } /** * Gets the raw `Response` instance instead of parsing the response @@ -77130,7 +70885,7 @@ class api_promise_APIPromise extends Promise { } parse() { if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), data)); } return this.parsedPromise; } @@ -77144,7 +70899,7 @@ class api_promise_APIPromise extends Promise { return this.parse().finally(onfinally); } } -_APIPromise_client = new WeakMap(); +api_promise_APIPromise_client = new WeakMap(); //# sourceMappingURL=api-promise.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/pagination.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -77245,7 +71000,7 @@ class pagination_Page extends pagination_AbstractPage { return { ...this.options, query: { - ...maybeObj(this.options.query), + ...values_maybeObj(this.options.query), before_id: first_id, }, }; @@ -77257,7 +71012,7 @@ class pagination_Page extends pagination_AbstractPage { return { ...this.options, query: { - ...maybeObj(this.options.query), + ...values_maybeObj(this.options.query), after_id: cursor, }, }; @@ -77266,7 +71021,7 @@ class pagination_Page extends pagination_AbstractPage { //# sourceMappingURL=pagination.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/uploads.mjs -const checkFileSupport = () => { +const uploads_checkFileSupport = () => { if (typeof File === 'undefined') { const { process } = globalThis; const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; @@ -77280,8 +71035,8 @@ const checkFileSupport = () => { * Construct a `File` instance. This is used to ensure a helpful error is thrown * for environments that don't define a global `File` yet. */ -function makeFile(fileBits, fileName, options) { - checkFileSupport(); +function uploads_makeFile(fileBits, fileName, options) { + uploads_checkFileSupport(); return new File(fileBits, fileName ?? 'unknown_file', options); } function uploads_getName(value) { @@ -77295,7 +71050,7 @@ function uploads_getName(value) { .split(/[\\/]/) .pop() || undefined); } -const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +const uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; /** * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. * Otherwise returns the request as is. @@ -77308,16 +71063,16 @@ const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { const uploads_multipartFormRequestOptions = async (opts, fetch) => { return { ...opts, body: await uploads_createForm(opts.body, fetch) }; }; -const supportsFormDataMap = new WeakMap(); +const uploads_supportsFormDataMap = new WeakMap(); /** * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". * This function detects if the fetch function provided supports the global FormData object to avoid * confusing error messages later on. */ -function supportsFormData(fetchObject) { +function uploads_supportsFormData(fetchObject) { const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; - const cached = supportsFormDataMap.get(fetch); + const cached = uploads_supportsFormDataMap.get(fetch); if (cached) return cached; const promise = (async () => { @@ -77336,11 +71091,11 @@ function supportsFormData(fetchObject) { return true; } })(); - supportsFormDataMap.set(fetch, promise); + uploads_supportsFormDataMap.set(fetch, promise); return promise; } const uploads_createForm = async (body, fetch) => { - if (!(await supportsFormData(fetch))) { + if (!(await uploads_supportsFormData(fetch))) { throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); } const form = new FormData(); @@ -77349,10 +71104,10 @@ const uploads_createForm = async (body, fetch) => { }; // We check for Blob not File because Bun.File doesn't inherit from File, // but they both inherit from Blob and have a `name` property at runtime. -const isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const uploads_isNamedBlob = (value) => value instanceof Blob && 'name' in value; const uploads_isUploadable = (value) => typeof value === 'object' && value !== null && - (value instanceof Response || isAsyncIterable(value) || isNamedBlob(value)); + (value instanceof Response || uploads_isAsyncIterable(value) || uploads_isNamedBlob(value)); const uploads_hasUploadableValue = (value) => { if (uploads_isUploadable(value)) return true; @@ -77382,13 +71137,13 @@ const uploads_addFormValue = async (form, key, value) => { if (contentType) { options = { type: contentType }; } - form.append(key, makeFile([await value.blob()], uploads_getName(value), options)); + form.append(key, uploads_makeFile([await value.blob()], uploads_getName(value), options)); } - else if (isAsyncIterable(value)) { - form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], uploads_getName(value))); + else if (uploads_isAsyncIterable(value)) { + form.append(key, uploads_makeFile([await new Response(shims_ReadableStreamFrom(value)).blob()], uploads_getName(value))); } - else if (isNamedBlob(value)) { - form.append(key, makeFile([value], uploads_getName(value), { type: value.type })); + else if (uploads_isNamedBlob(value)) { + form.append(key, uploads_makeFile([value], uploads_getName(value), { type: value.type })); } else if (Array.isArray(value)) { await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); @@ -77436,7 +71191,7 @@ const to_file_isResponseLike = (value) => value != null && * @returns a {@link File} with the given properties */ async function to_file_toFile(value, name, options) { - checkFileSupport(); + uploads_checkFileSupport(); // If it's a promise, resolve it. value = await value; name || (name = uploads_getName(value)); @@ -77446,7 +71201,7 @@ async function to_file_toFile(value, name, options) { if (value instanceof File && name == null && options == null) { return value; } - return makeFile([await value.arrayBuffer()], name ?? value.name, { + return uploads_makeFile([await value.arrayBuffer()], name ?? value.name, { type: value.type, lastModified: value.lastModified, ...options, @@ -77455,7 +71210,7 @@ async function to_file_toFile(value, name, options) { if (to_file_isResponseLike(value)) { const blob = await value.blob(); name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile(await to_file_getBytes(blob), name, options); + return uploads_makeFile(await to_file_getBytes(blob), name, options); } const parts = await to_file_getBytes(value); if (!options?.type) { @@ -77464,7 +71219,7 @@ async function to_file_toFile(value, name, options) { options = { ...options, type }; } } - return makeFile(parts, name, options); + return uploads_makeFile(parts, name, options); } async function to_file_getBytes(value) { let parts = []; @@ -77476,7 +71231,7 @@ async function to_file_getBytes(value) { else if (to_file_isBlobLike(value)) { parts.push(value instanceof Blob ? value : await value.arrayBuffer()); } - else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc. + else if (uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. ) { for await (const chunk of value) { parts.push(...(await to_file_getBytes(chunk))); // TODO, consider validating? @@ -77508,12 +71263,12 @@ class resource_APIResource { //# sourceMappingURL=resource.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/headers.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); -const isArray = Array.isArray; -function* iterateHeaders(headers) { +const headers_brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +const headers_isArray = Array.isArray; +function* headers_iterateHeaders(headers) { if (!headers) return; - if (brand_privateNullableHeaders in headers) { + if (headers_brand_privateNullableHeaders in headers) { const { values, nulls } = headers; yield* values.entries(); for (const name of nulls) { @@ -77526,7 +71281,7 @@ function* iterateHeaders(headers) { if (headers instanceof Headers) { iter = headers.entries(); } - else if (isArray(headers)) { + else if (headers_isArray(headers)) { iter = headers; } else { @@ -77537,7 +71292,7 @@ function* iterateHeaders(headers) { const name = row[0]; if (typeof name !== 'string') throw new TypeError('expected header name to be a string'); - const values = isArray(row[1]) ? row[1] : [row[1]]; + const values = headers_isArray(row[1]) ? row[1] : [row[1]]; let didClear = false; for (const value of values) { if (value === undefined) @@ -77552,12 +71307,12 @@ function* iterateHeaders(headers) { } } } -const buildHeaders = (newHeaders) => { +const headers_buildHeaders = (newHeaders) => { const targetHeaders = new Headers(); const nullHeaders = new Set(); for (const headers of newHeaders) { const seenHeaders = new Set(); - for (const [name, value] of iterateHeaders(headers)) { + for (const [name, value] of headers_iterateHeaders(headers)) { const lowerName = name.toLowerCase(); if (!seenHeaders.has(lowerName)) { targetHeaders.delete(name); @@ -77573,10 +71328,10 @@ const buildHeaders = (newHeaders) => { } } } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; + return { [headers_brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; }; -const isEmptyHeaders = (headers) => { - for (const _ of iterateHeaders(headers)) +const headers_isEmptyHeaders = (headers) => { + for (const _ of headers_iterateHeaders(headers)) return false; return true; }; @@ -77591,10 +71346,10 @@ const isEmptyHeaders = (headers) => { * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" */ -function encodeURIPath(str) { +function path_encodeURIPath(str) { return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } -const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { +const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => function path(statics, ...params) { // If there are no params, no processing is needed. if (statics.length === 1) return statics[0]; @@ -77633,7 +71388,7 @@ const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(sta /** * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. */ -const path = createPathTagFunction(encodeURIPath); +const path_path = path_createPathTagFunction(path_encodeURIPath); //# sourceMappingURL=path.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/files.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -77659,7 +71414,7 @@ class beta_files_Files extends resource_APIResource { return this._client.getAPIList('/v1/files', (pagination_Page), { query, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, options?.headers, ]), @@ -77677,9 +71432,9 @@ class beta_files_Files extends resource_APIResource { */ delete(fileID, params = {}, options) { const { betas } = params ?? {}; - return this._client.delete(path `/v1/files/${fileID}`, { + return this._client.delete(path_path `/v1/files/${fileID}`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, options?.headers, ]), @@ -77700,9 +71455,9 @@ class beta_files_Files extends resource_APIResource { */ download(fileID, params = {}, options) { const { betas } = params ?? {}; - return this._client.get(path `/v1/files/${fileID}/content`, { + return this._client.get(path_path `/v1/files/${fileID}/content`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), Accept: 'application/binary', @@ -77723,9 +71478,9 @@ class beta_files_Files extends resource_APIResource { */ retrieveMetadata(fileID, params = {}, options) { const { betas } = params ?? {}; - return this._client.get(path `/v1/files/${fileID}`, { + return this._client.get(path_path `/v1/files/${fileID}`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, options?.headers, ]), @@ -77746,7 +71501,7 @@ class beta_files_Files extends resource_APIResource { return this._client.post('/v1/files', uploads_multipartFormRequestOptions({ body, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, options?.headers, ]), @@ -77776,9 +71531,9 @@ class models_Models extends resource_APIResource { */ retrieve(modelID, params = {}, options) { const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}?beta=true`, { + return this._client.get(path_path `/v1/models/${modelID}?beta=true`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), @@ -77803,7 +71558,7 @@ class models_Models extends resource_APIResource { return this._client.getAPIList('/v1/models?beta=true', (pagination_Page), { query, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), @@ -77893,7 +71648,7 @@ class batches_Batches extends resource_APIResource { return this._client.post('/v1/messages/batches?beta=true', { body, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, options?.headers, ]), @@ -77917,9 +71672,9 @@ class batches_Batches extends resource_APIResource { */ retrieve(messageBatchID, params = {}, options) { const { betas } = params ?? {}; - return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, { + return this._client.get(path_path `/v1/messages/batches/${messageBatchID}?beta=true`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, options?.headers, ]), @@ -77945,7 +71700,7 @@ class batches_Batches extends resource_APIResource { return this._client.getAPIList('/v1/messages/batches?beta=true', (pagination_Page), { query, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, options?.headers, ]), @@ -77970,9 +71725,9 @@ class batches_Batches extends resource_APIResource { */ delete(messageBatchID, params = {}, options) { const { betas } = params ?? {}; - return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, { + return this._client.delete(path_path `/v1/messages/batches/${messageBatchID}?beta=true`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, options?.headers, ]), @@ -78002,9 +71757,9 @@ class batches_Batches extends resource_APIResource { */ cancel(messageBatchID, params = {}, options) { const { betas } = params ?? {}; - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + return this._client.post(path_path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, options?.headers, ]), @@ -78037,7 +71792,7 @@ class batches_Batches extends resource_APIResource { return this._client .get(batch.results_url, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), Accept: 'application/binary', @@ -78311,7 +72066,7 @@ class BetaMessageStream { _BetaMessageStream_request_id.set(this, void 0); _BetaMessageStream_handleError.set(this, (error) => { tslib_classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); - if (isAbortError(error)) { + if (errors_isAbortError(error)) { error = new error_APIUserAbortError(); } if (error instanceof error_APIUserAbortError) { @@ -78887,7 +72642,7 @@ class messages_messages_Messages extends resource_APIResource { body, timeout: timeout ?? 600000, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), @@ -78923,7 +72678,7 @@ class messages_messages_Messages extends resource_APIResource { return this._client.post('/v1/messages/count_tokens?beta=true', { body, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, options?.headers, ]), @@ -78964,7 +72719,7 @@ class resources_completions_Completions extends resource_APIResource { body, timeout: this._client._options.timeout ?? 600000, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), @@ -79006,7 +72761,7 @@ class MessageStream { _MessageStream_request_id.set(this, void 0); _MessageStream_handleError.set(this, (error) => { tslib_classPrivateFieldSet(this, _MessageStream_errored, true, "f"); - if (isAbortError(error)) { + if (errors_isAbortError(error)) { error = new error_APIUserAbortError(); } if (error instanceof error_APIUserAbortError) { @@ -79582,7 +73337,7 @@ class messages_batches_Batches extends resource_APIResource { * ``` */ retrieve(messageBatchID, options) { - return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); + return this._client.get(path_path `/v1/messages/batches/${messageBatchID}`, options); } /** * List all Message Batches within a Workspace. Most recently created batches are @@ -79618,7 +73373,7 @@ class messages_batches_Batches extends resource_APIResource { * ``` */ delete(messageBatchID, options) { - return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); + return this._client.delete(path_path `/v1/messages/batches/${messageBatchID}`, options); } /** * Batches may be canceled any time before processing ends. Once cancellation is @@ -79642,7 +73397,7 @@ class messages_batches_Batches extends resource_APIResource { * ``` */ cancel(messageBatchID, options) { - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); + return this._client.post(path_path `/v1/messages/batches/${messageBatchID}/cancel`, options); } /** * Streams the results of a Message Batch as a `.jsonl` file. @@ -79668,7 +73423,7 @@ class messages_batches_Batches extends resource_APIResource { return this._client .get(batch.results_url, { ...options, - headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), stream: true, __binaryResponse: true, }) @@ -79759,9 +73514,9 @@ class resources_models_Models extends resource_APIResource { */ retrieve(modelID, params = {}, options) { const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}`, { + return this._client.get(path_path `/v1/models/${modelID}`, { ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), @@ -79778,7 +73533,7 @@ class resources_models_Models extends resource_APIResource { return this._client.getAPIList('/v1/models', (pagination_Page), { query, ...options, - headers: buildHeaders([ + headers: headers_buildHeaders([ { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, options?.headers, ]), @@ -79815,7 +73570,7 @@ const env_readEnv = (env) => { //# sourceMappingURL=env.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/client.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var client_a, _BaseAnthropic_encoder; +var sdk_client_a, _BaseAnthropic_encoder; @@ -79873,13 +73628,13 @@ class BaseAnthropic { // Set default logLevel early so that we can log a warning in parseLogLevel. this.logLevel = defaultLogLevel; this.logLevel = - parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - parseLogLevel(env_readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? + log_parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + log_parseLogLevel(env_readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel; this.fetchOptions = options.fetchOptions; this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - tslib_classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); + this.fetch = options.fetch ?? shims_getDefaultFetch(); + tslib_classPrivateFieldSet(this, _BaseAnthropic_encoder, request_options_FallbackEncoder, "f"); this._options = options; this.apiKey = apiKey; this.authToken = authToken; @@ -79920,19 +73675,19 @@ class BaseAnthropic { throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); } authHeaders(opts) { - return buildHeaders([this.apiKeyAuth(opts), this.bearerAuth(opts)]); + return headers_buildHeaders([this.apiKeyAuth(opts), this.bearerAuth(opts)]); } apiKeyAuth(opts) { if (this.apiKey == null) { return undefined; } - return buildHeaders([{ 'X-Api-Key': this.apiKey }]); + return headers_buildHeaders([{ 'X-Api-Key': this.apiKey }]); } bearerAuth(opts) { if (this.authToken == null) { return undefined; } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + return headers_buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); } /** * Basic re-implementation of `qs.stringify` for primitive types. @@ -80029,7 +73784,7 @@ class BaseAnthropic { const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + log_loggerFor(this).debug(`[${requestLogID}] sending request`, log_formatRequestDetails({ retryOfRequestLogID, method: options.method, url, @@ -80051,11 +73806,11 @@ class BaseAnthropic { // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = isAbortError(response) || + const isTimeout = errors_isAbortError(response) || /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ + log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, log_formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, @@ -80063,8 +73818,8 @@ class BaseAnthropic { })); return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ + log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, log_formatRequestDetails({ retryOfRequestLogID, url, durationMs: headersTime - startTime, @@ -80085,9 +73840,9 @@ class BaseAnthropic { if (retriesRemaining && shouldRetry) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; // We don't need the body of this response. - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + await shims_CancelReadableStream(response.body); + log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, @@ -80097,11 +73852,11 @@ class BaseAnthropic { return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); } const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); const errText = await response.text().catch((err) => errors_castToError(err).message); const errJSON = values_safeJSON(errText); const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, @@ -80112,8 +73867,8 @@ class BaseAnthropic { const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); throw err; } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + log_loggerFor(this).info(responseInfo); + log_loggerFor(this).debug(`[${requestLogID}] response start`, log_formatRequestDetails({ retryOfRequestLogID, url: response.url, status: response.status, @@ -80254,7 +74009,7 @@ class BaseAnthropic { options.idempotencyKey = this.defaultIdempotencyKey(); idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; } - const headers = buildHeaders([ + const headers = headers_buildHeaders([ idempotencyHeaders, { Accept: 'application/json', @@ -80279,7 +74034,7 @@ class BaseAnthropic { if (!body) { return { bodyHeaders: undefined, body: undefined }; } - const headers = buildHeaders([rawHeaders]); + const headers = headers_buildHeaders([rawHeaders]); if ( // Pass raw type verbatim ArrayBuffer.isView(body) || @@ -80301,15 +74056,15 @@ class BaseAnthropic { else if (typeof body === 'object' && (Symbol.asyncIterator in body || (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; + return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; } else { return tslib_classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); } } } -client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(); -BaseAnthropic.Anthropic = client_a; +sdk_client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(); +BaseAnthropic.Anthropic = sdk_client_a; BaseAnthropic.HUMAN_PROMPT = '\n\nHuman:'; BaseAnthropic.AI_PROMPT = '\n\nAssistant:'; BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes @@ -81858,7 +75613,7 @@ class function_FunctionMessageChunk extends BaseMessageChunk { }); } } -function function_isFunctionMessage(x) { +function isFunctionMessage(x) { return x._getType() === "function"; } function isFunctionMessageChunk(x) { @@ -86882,7 +80637,7 @@ var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; var arr = []; var replacerStack = []; const encoder = new TextEncoder(); -function fast_safe_stringify_defaultOptions() { +function defaultOptions() { return { depthLimit: Number.MAX_SAFE_INTEGER, edgesLimit: Number.MAX_SAFE_INTEGER, @@ -86905,7 +80660,7 @@ function serialize(obj, errorContext, replacer, spacer, options) { } console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); if (typeof options === "undefined") { - options = fast_safe_stringify_defaultOptions(); + options = defaultOptions(); } decirc(obj, "", 0, [], undefined, 0, options); let res; @@ -86999,7 +80754,7 @@ function compareFunction(a, b) { } function deterministicStringify(obj, replacer, spacer, options) { if (typeof options === "undefined") { - options = fast_safe_stringify_defaultOptions(); + options = defaultOptions(); } var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; var res; @@ -96766,7 +90521,7 @@ const allowsEval = cached(() => { function _isObject(o) { return Object.prototype.toString.call(o) === "[object Object]"; } -function core_util_isPlainObject(o) { +function isPlainObject(o) { if (isObject(o) === false) return false; // modified constructor @@ -120326,6 +114081,82 @@ Either provide one via the "apiKey" field in the constructor, or set the "MISTRA // EXTERNAL MODULE: ./node_modules/parse-diff/index.js var parse_diff = __nccwpck_require__(2673); +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Options.mjs +const Options_ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); +const zod_to_json_schema_Options_defaultOptions = { + name: undefined, + $refStrategy: 'root', + effectStrategy: 'input', + pipeStrategy: 'all', + dateStrategy: 'format:date-time', + mapStrategy: 'entries', + nullableStrategy: 'from-target', + removeAdditionalStrategy: 'passthrough', + definitionPath: 'definitions', + target: 'jsonSchema7', + strictUnions: false, + errorMessages: false, + markdownDescription: false, + patternStrategy: 'escape', + applyRegexFlags: false, + emailStrategy: 'format:email', + base64Strategy: 'contentEncoding:base64', + nameStrategy: 'ref', +}; +const Options_getDefaultOptions = (options) => { + // We need to add `definitions` here as we may mutate it + return (typeof options === 'string' ? + { + ...zod_to_json_schema_Options_defaultOptions, + basePath: ['#'], + definitions: {}, + name: options, + } + : { + ...zod_to_json_schema_Options_defaultOptions, + basePath: ['#'], + definitions: {}, + ...options, + }); +}; +//# sourceMappingURL=Options.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/util.mjs +const zodDef = (zodSchema) => { + return '_def' in zodSchema ? zodSchema._def : zodSchema; +}; +function util_isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +//# sourceMappingURL=util.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs + + +const Refs_getRefs = (options) => { + const _options = Options_getDefaultOptions(options); + const currentPath = _options.name !== undefined ? + [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + currentPath: currentPath, + propertyPath: undefined, + seenRefs: new Set(), + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + zodDef(def), + { + def: zodDef(def), + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; +//# sourceMappingURL=Refs.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs function any_parseAnyDef() { return {}; @@ -120828,8 +114659,8 @@ const processRegExp = (regexOrFunction, refs) => { return regex.source; // Currently handled flags const flags = { - i: regex.flags.includes('i'), - m: regex.flags.includes('m'), + i: regex.flags.includes('i'), // Case-insensitive + m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters s: regex.flags.includes('s'), // `.` matches newlines }; // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! @@ -121207,8 +115038,11 @@ function object_parseObjectDef(def, refs) { }); if (parsedDef === undefined) return acc; - if (refs.openaiStrictMode && propDef.isOptional() && !propDef.isNullable()) { - console.warn(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required\nThis will become an error in a future version of the SDK.`); + if (refs.openaiStrictMode && + propDef.isOptional() && + !propDef.isNullable() && + typeof propDef._def?.defaultValue === 'undefined') { + throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); } return { properties: { @@ -121349,45 +115183,6 @@ const readonly_parseReadonlyDef = (def, refs) => { return parseDef_parseDef(def.innerType._def, refs); }; //# sourceMappingURL=readonly.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Options.mjs -const Options_ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); -const zod_to_json_schema_Options_defaultOptions = { - name: undefined, - $refStrategy: 'root', - effectStrategy: 'input', - pipeStrategy: 'all', - dateStrategy: 'format:date-time', - mapStrategy: 'entries', - nullableStrategy: 'from-target', - removeAdditionalStrategy: 'passthrough', - definitionPath: 'definitions', - target: 'jsonSchema7', - strictUnions: false, - errorMessages: false, - markdownDescription: false, - patternStrategy: 'escape', - applyRegexFlags: false, - emailStrategy: 'format:email', - base64Strategy: 'contentEncoding:base64', - nameStrategy: 'ref', -}; -const Options_getDefaultOptions = (options) => { - // We need to add `definitions` here as we may mutate it - return (typeof options === 'string' ? - { - ...zod_to_json_schema_Options_defaultOptions, - basePath: ['#'], - definitions: {}, - name: options, - } - : { - ...zod_to_json_schema_Options_defaultOptions, - basePath: ['#'], - definitions: {}, - ...options, - }); -}; -//# sourceMappingURL=Options.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs @@ -121572,43 +115367,6 @@ const parseDef_addMeta = (def, refs, jsonSchema) => { return jsonSchema; }; //# sourceMappingURL=parseDef.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/util.mjs -const zodDef = (zodSchema) => { - return '_def' in zodSchema ? zodSchema._def : zodSchema; -}; -function util_isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -//# sourceMappingURL=util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs - - -const Refs_getRefs = (options) => { - const _options = Options_getDefaultOptions(options); - const currentPath = _options.name !== undefined ? - [..._options.basePath, _options.definitionPath, _options.name] - : _options.basePath; - return { - ..._options, - currentPath: currentPath, - propertyPath: undefined, - seenRefs: new Set(), - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - zodDef(def), - { - def: zodDef(def), - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: undefined, - }, - ])), - }; -}; -//# sourceMappingURL=Refs.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs @@ -121689,6 +115447,45 @@ const zod_to_json_schema_zodToJsonSchema_zodToJsonSchema = (schema, options) => }; //# sourceMappingURL=zodToJsonSchema.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/index.mjs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* harmony default export */ const zod_to_json_schema = ((/* unused pure expression or super */ null && (zodToJsonSchema))); +//# sourceMappingURL=index.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/helpers/zod.mjs @@ -121712,7 +115509,7 @@ function zod_zodToJsonSchema(schema, options) { * the given Zod object. * * ```ts - * const completion = await client.beta.chat.completions.parse({ + * const completion = await client.chat.completions.parse({ * model: 'gpt-4o-2024-08-06', * messages: [ * { role: 'system', content: 'You are a helpful math tutor.' }, @@ -122472,11 +116269,11 @@ function log({ withTimestamp = true }) { * @returns {AIPlatformSDK | Error} The AI platform SDK instance. */ function getPlatformSDK(platform, apiKey) { - if (platform === "openai") return new openai({ apiKey }); + if (platform === "openai") return new OpenAI({ apiKey }); if (platform === "anthropic") return new Anthropic({ apiKey }); if (platform === "mistral") return new ChatMistralAI({ apiKey }); - if (platform === "openrouter") return new openai({ apiKey, baseURL: BASE_URL.OPENROUTER }); - if (platform === "google") return new openai({ apiKey, baseURL: BASE_URL.GOOGLE }); + if (platform === "openrouter") return new OpenAI({ apiKey, baseURL: BASE_URL.OPENROUTER }); + if (platform === "google") return new OpenAI({ apiKey, baseURL: BASE_URL.GOOGLE }); throw new Error(`Unsupported AI platform: ${platform}`); } diff --git a/dist/licenses.txt b/dist/licenses.txt index cb8e1a1..592976f 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -1,8 +1,1404 @@ -formdata-node +@actions/core MIT The MIT License (MIT) -Copyright (c) 2017-present Nick K. +Copyright 2019 GitHub + +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. + +@actions/exec +MIT +The MIT License (MIT) + +Copyright 2019 GitHub + +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. + +@actions/github +MIT +The MIT License (MIT) + +Copyright 2019 GitHub + +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. + +@actions/http-client +MIT +Actions Http Client for Node.js + +Copyright (c) GitHub, Inc. + +All rights reserved. + +MIT License + +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. + + +@actions/io +MIT +The MIT License (MIT) + +Copyright 2019 GitHub + +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. + +@anthropic-ai/sdk +MIT +Copyright 2023 Anthropic, PBC. + +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. + + + +@cfworker/json-schema +MIT + +@fastify/busboy +MIT +Copyright Brian White. 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. + +@langchain/core +MIT +The MIT License + +Copyright (c) Harrison Chase + +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. + +@langchain/mistralai +MIT +The MIT License + +Copyright (c) 2023 LangChain + +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. + +@mistralai/mistralai + 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 Mistral AI + + 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. + + +@octokit/auth-token +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/core +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +@octokit/endpoint +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/graphql +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/plugin-paginate-rest +MIT +MIT License Copyright (c) 2019 Octokit 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 (including the next paragraph) 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. + + +@octokit/plugin-rest-endpoint-methods +MIT +MIT License Copyright (c) 2019 Octokit 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 (including the next paragraph) 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. + + +@octokit/request +MIT +The MIT License + +Copyright (c) 2018 Octokit 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. + + +@octokit/request-error +MIT +The MIT License + +Copyright (c) 2019 Octokit 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. + + +ansi-styles +MIT +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. + + +base64-js +MIT +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +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. + + +before-after-hook +Apache-2.0 + 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 2018 Gregor Martynus and other contributors. + + 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. + + +braces +MIT +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +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. + + +camelcase +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://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. + + +decamelize +MIT +The MIT License (MIT) + +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. + + +deprecation +ISC +The ISC License + +Copyright (c) Gregor Martynus and contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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. + + +eventemitter3 +MIT +The MIT License (MIT) + +Copyright (c) 2014 Arnout Kazemier + +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. + + +fill-range +MIT +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +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. + + +is-number +MIT +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +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. + + +js-tiktoken +MIT + +langsmith +MIT + +micromatch +MIT +The MIT License (MIT) + +Copyright (c) 2014-present, Jon Schlinkert. + +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. + + +once +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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. + + +openai +Apache-2.0 + 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 2025 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. + + +p-finally +MIT +The MIT License (MIT) + +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. + + +p-queue +MIT +MIT License + +Copyright (c) Sindre Sorhus (https://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. + + +p-retry +MIT +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. + + +p-timeout +MIT +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. + + +parse-diff +MIT +The MIT License (MIT) + +Copyright (c) 2014 Sergey Todyshev + +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. + + +picomatch +MIT +The MIT License (MIT) + +Copyright (c) 2017-present, Jon Schlinkert. + +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. + + +retry +MIT +Copyright (c) 2011: +Tim Koschützki (tim@debuggable.com) +Felix Geisendörfer (felix@debuggable.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. + + +semver +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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. + + +to-regex-range +MIT +The MIT License (MIT) + +Copyright (c) 2015-present, Jon Schlinkert. + +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. + + +tunnel +MIT +The MIT License (MIT) + +Copyright (c) 2012 Koichi Kobayashi + +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. + + +undici +MIT +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 @@ -23,11 +1419,54 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -node-domexception +universal-user-agent +ISC +# [ISC License](https://spdx.org/licenses/ISC) + +Copyright (c) 2018, Gregor Martynus (https://github.com/gr2m) + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +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. + + +uuid +MIT +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other 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. + + +wrappy +ISC +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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. + + +zod MIT MIT License -Copyright (c) 2021 Jimmy Wärting +Copyright (c) 2025 Colin McDonnell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -46,3 +1485,22 @@ 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. + + +zod-to-json-schema +ISC +ISC License + +Copyright (c) 2020, Stefan Terdell + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +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/package-lock.json b/package-lock.json index 0583212..7b0fec1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "@langchain/mistralai": "^0.2.1", "is-ci": "^4.1.0", "micromatch": "^4.0.8", - "openai": "^4.98.0", + "openai": "^5.3.0", "parse-diff": "^0.11.1", "zod": "^3.25.64", "zod-to-json-schema": "^3.24.5" @@ -590,25 +590,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/node": { - "version": "18.19.100", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.100.tgz", - "integrity": "sha512-ojmMP8SZBKprc3qGrGk8Ujpo80AXkrP7G2tOT4VWr5jlr5DHjsJF+emXJz+Wm0glmy4Js62oKMdZZ6B9Y+tEcA==", - "license": "MIT", - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/@types/node-fetch": { - "version": "2.6.12", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.12.tgz", - "integrity": "sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA==", - "license": "MIT", - "dependencies": { - "@types/node": "*", - "form-data": "^4.0.0" - } - }, "node_modules/@types/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", @@ -645,18 +626,6 @@ "ncc": "dist/ncc/cli.js" } }, - "node_modules/abort-controller": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", - "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", - "license": "MIT", - "dependencies": { - "event-target-shim": "^5.0.0" - }, - "engines": { - "node": ">=6.5" - } - }, "node_modules/acorn": { "version": "8.15.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", @@ -680,18 +649,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/agentkeepalive": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", - "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", - "license": "MIT", - "dependencies": { - "humanize-ms": "^1.2.1" - }, - "engines": { - "node": ">= 8.0.0" - } - }, "node_modules/ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", @@ -810,12 +767,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "license": "MIT" - }, "node_modules/available-typed-arrays": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", @@ -912,6 +863,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -1049,18 +1001,6 @@ "dev": true, "license": "MIT" }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/commander": { "version": "14.0.0", "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.0.tgz", @@ -1236,15 +1176,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/deprecation": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", @@ -1255,6 +1186,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", @@ -1360,6 +1292,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -1369,6 +1302,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -1378,6 +1312,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -1390,6 +1325,7 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -1641,15 +1577,6 @@ "node": ">=0.10.0" } }, - "node_modules/event-target-shim": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", - "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/eventemitter3": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", @@ -1751,65 +1678,11 @@ "is-callable": "^1.1.3" } }, - "node_modules/form-data": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz", - "integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==", - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/form-data-encoder": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", - "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", - "license": "MIT" - }, - "node_modules/form-data/node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/form-data/node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/formdata-node": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", - "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", - "license": "MIT", - "dependencies": { - "node-domexception": "1.0.0", - "web-streams-polyfill": "4.0.0-beta.3" - }, - "engines": { - "node": ">= 12.20" - } - }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -1861,6 +1734,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -1885,6 +1759,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", @@ -1959,6 +1834,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2023,6 +1899,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2035,6 +1912,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, "license": "MIT", "dependencies": { "has-symbols": "^1.0.3" @@ -2050,6 +1928,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -2065,15 +1944,6 @@ "dev": true, "license": "ISC" }, - "node_modules/humanize-ms": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", - "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", - "license": "MIT", - "dependencies": { - "ms": "^2.0.0" - } - }, "node_modules/husky": { "version": "9.1.7", "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", @@ -2745,6 +2615,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2802,6 +2673,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, "license": "MIT" }, "node_modules/mustache": { @@ -2840,46 +2712,6 @@ "dev": true, "license": "MIT" }, - "node_modules/node-domexception": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", - "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", - "deprecated": "Use your platform's native DOMException instead", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "engines": { - "node": ">=10.5.0" - } - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, "node_modules/normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", @@ -3176,19 +3008,10 @@ } }, "node_modules/openai": { - "version": "4.98.0", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.98.0.tgz", - "integrity": "sha512-TmDKur1WjxxMPQAtLG5sgBSCJmX7ynTsGmewKzoDwl1fRxtbLOsiR0FA/AOAAtYUmP6azal+MYQuOENfdU+7yg==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-5.3.0.tgz", + "integrity": "sha512-VIKmoF7y4oJCDOwP/oHXGzM69+x0dpGFmN9QmYO+uPbLFOmmnwO+x1GbsgUtI+6oraxomGZ566Y421oYVu191w==", "license": "Apache-2.0", - "dependencies": { - "@types/node": "^18.11.18", - "@types/node-fetch": "^2.6.4", - "abort-controller": "^3.0.0", - "agentkeepalive": "^4.2.1", - "form-data-encoder": "1.7.2", - "formdata-node": "^4.3.2", - "node-fetch": "^2.6.7" - }, "bin": { "openai": "bin/cli" }, @@ -4070,12 +3893,6 @@ "node": ">=8.0" } }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT" - }, "node_modules/tunnel": { "version": "0.0.6", "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", @@ -4203,12 +4020,6 @@ "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==", - "license": "MIT" - }, "node_modules/universal-user-agent": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", @@ -4260,31 +4071,6 @@ "spdx-license-ids": "^3.0.0" } }, - "node_modules/web-streams-polyfill": { - "version": "4.0.0-beta.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", - "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause" - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index e94d43a..516038a 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "@langchain/mistralai": "^0.2.1", "is-ci": "^4.1.0", "micromatch": "^4.0.8", - "openai": "^4.98.0", + "openai": "^5.3.0", "parse-diff": "^0.11.1", "zod": "^3.25.64", "zod-to-json-schema": "^3.24.5" From 6cb22ead91a123d73c63cd89cbe56010359dc714 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 21:32:54 +0530 Subject: [PATCH 09/14] feat: from beta to stable completions api --- dist/index.js | 2 +- index.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/index.js b/dist/index.js index a8e9683..f54c2aa 100644 --- a/dist/index.js +++ b/dist/index.js @@ -115857,7 +115857,7 @@ function getUserPrompt(rules, rawComments, pullRequestContext) { async function useOpenAI({ rawComments, openAI, rules, modelName, pullRequestContext, platform }) { const modelDeepseek = /deepseek/i.test(getModelName(modelName, platform)); const result = !modelDeepseek - ? await openAI.beta.chat.completions.parse({ + ? await openAI.chat.completions.parse({ model: getModelName(modelName, platform), messages: [ { diff --git a/index.js b/index.js index 1ed9b86..7dc1fd3 100644 --- a/index.js +++ b/index.js @@ -174,7 +174,7 @@ function getUserPrompt(rules, rawComments, pullRequestContext) { async function useOpenAI({ rawComments, openAI, rules, modelName, pullRequestContext, platform }) { const modelDeepseek = /deepseek/i.test(getModelName(modelName, platform)); const result = !modelDeepseek - ? await openAI.beta.chat.completions.parse({ + ? await openAI.chat.completions.parse({ model: getModelName(modelName, platform), messages: [ { From 3b8e1194e0de4d439cbcb4804af95fbcfa8af137 Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 21:45:36 +0530 Subject: [PATCH 10/14] feat: from beta to stable completions api --- dist/index.js | 1 + index.js | 1 + 2 files changed, 2 insertions(+) diff --git a/dist/index.js b/dist/index.js index f54c2aa..282c4e5 100644 --- a/dist/index.js +++ b/dist/index.js @@ -116037,6 +116037,7 @@ async function retry( try { return await fn(); } catch (error) { + console.error(error) lastError = error; if (onRetry) { diff --git a/index.js b/index.js index 7dc1fd3..e16a7a7 100644 --- a/index.js +++ b/index.js @@ -354,6 +354,7 @@ async function retry( try { return await fn(); } catch (error) { + console.error(error); lastError = error; if (onRetry) { From bcd85dc202e657f3a5c145ed2e00ac0fb9c7e30a Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 22:46:52 +0530 Subject: [PATCH 11/14] fix: low severity issue --- dist/index.js | 2 +- package-lock.json | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dist/index.js b/dist/index.js index 282c4e5..f5714ac 100644 --- a/dist/index.js +++ b/dist/index.js @@ -116037,7 +116037,7 @@ async function retry( try { return await fn(); } catch (error) { - console.error(error) + console.error(error); lastError = error; if (onRetry) { diff --git a/package-lock.json b/package-lock.json index 7b0fec1..61bf169 100644 --- a/package-lock.json +++ b/package-lock.json @@ -817,9 +817,9 @@ "license": "Apache-2.0" }, "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, "license": "MIT", "dependencies": { From a5ae07b0c9fce0cf713f1b4d862a2afd771b2e3d Mon Sep 17 00:00:00 2001 From: murtuzaalisurti Date: Sun, 15 Jun 2025 22:59:45 +0530 Subject: [PATCH 12/14] chore: remove redundant log --- dist/index.js | 1 - index.js | 1 - 2 files changed, 2 deletions(-) diff --git a/dist/index.js b/dist/index.js index f5714ac..f54c2aa 100644 --- a/dist/index.js +++ b/dist/index.js @@ -116037,7 +116037,6 @@ async function retry( try { return await fn(); } catch (error) { - console.error(error); lastError = error; if (onRetry) { diff --git a/index.js b/index.js index e16a7a7..7dc1fd3 100644 --- a/index.js +++ b/index.js @@ -354,7 +354,6 @@ async function retry( try { return await fn(); } catch (error) { - console.error(error); lastError = error; if (onRetry) { From 068e6fdbb9e25a6cf5e234fd4e40d9473cd881c7 Mon Sep 17 00:00:00 2001 From: Murtuzaali Surti <68743212+murtuzaalisurti@users.noreply.github.com> Date: Sun, 10 Aug 2025 20:53:24 +0530 Subject: [PATCH 13/14] feat: update openai's default model to gpt-5 and upgrade deps (#16) --- README.md | 2 +- dist/index.js | 13836 +++++++++++++++++++++++++------------------ package-lock.json | 243 +- package.json | 26 +- utils/constants.js | 2 +- 5 files changed, 8138 insertions(+), 5971 deletions(-) diff --git a/README.md b/README.md index 36f7ef6..9c0d9bf 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ They can be accessed in the workflow file using `${{ secrets.YOUR_KEY_NAME }}`. ### 4. `ai-model-name` (Optional) -Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-4.1-2025-04-14` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-06-05` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `google/gemini-2.5-pro-preview-06-05` for OpenRouter if not specified. Here's a list of supported models: +Specify the name of the model you want to use to generate suggestions. Fallbacks to `gpt-5` for OpenAI, `claude-3-7-sonnet-latest` for Anthropic, `gemini-2.5-pro-preview-06-05` for Google's Gemini, `pixtral-12b-2409` for Mistral, and `google/gemini-2.5-pro-preview-06-05` for OpenRouter if not specified. Here's a list of supported models: For OpenAI: diff --git a/dist/index.js b/dist/index.js index f54c2aa..5a4bafa 100644 --- a/dist/index.js +++ b/dist/index.js @@ -62444,6 +62444,11 @@ class ContentFilterFinishReasonError extends error_OpenAIError { super(`Could not parse response content as the request was rejected by the content filter`); } } +class InvalidWebhookSignatureError extends Error { + constructor(message) { + super(message); + } +} //# sourceMappingURL=error.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/values.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -62453,6 +62458,8 @@ const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; const isAbsoluteURL = (url) => { return startsWithSchemeRegexp.test(url); }; +let values_isArray = (val) => ((values_isArray = Array.isArray), values_isArray(val)); +let isReadonlyArray = values_isArray; /** Returns an object if the given value isn't an object, otherwise returns as-is */ function maybeObj(x) { if (typeof x !== 'object') { @@ -62542,88 +62549,8 @@ const safeJSON = (text) => { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); //# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; - } - if (hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; - } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return undefined; -}; -function noop() { } -function makeLogFn(fnLevel, logger, logLevel) { - if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; - } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); - } -} -const noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop, -}; -let cachedLoggers = new WeakMap(); -function loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return noopLogger; - } - const cachedLogger = cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: makeLogFn('error', logger, logLevel), - warn: makeLogFn('warn', logger, logLevel), - info: makeLogFn('info', logger, logLevel), - debug: makeLogFn('debug', logger, logLevel), - }; - cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -const formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); - } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; - } - delete details.retryOfRequestLogID; - } - return details; -}; -//# sourceMappingURL=log.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/version.mjs -const VERSION = '5.3.0'; // x-release-please-version +const VERSION = '5.12.2'; // x-release-please-version //# sourceMappingURL=version.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/detect-platform.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -62882,18 +62809,20 @@ const FallbackEncoder = ({ headers, body }) => { //# sourceMappingURL=request-options.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs const default_format = 'RFC3986'; +const default_formatter = (v) => String(v); const formatters = { RFC1738: (v) => String(v).replace(/%20/g, '+'), - RFC3986: (v) => String(v), + RFC3986: default_formatter, }; const RFC1738 = 'RFC1738'; const RFC3986 = 'RFC3986'; //# sourceMappingURL=formats.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs -const has = Object.prototype.hasOwnProperty; -const is_array = Array.isArray; -const hex_table = (() => { + +let has = (obj, key) => ((has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)), + has(obj, key)); +const hex_table = /* @__PURE__ */ (() => { const array = []; for (let i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); @@ -62906,7 +62835,7 @@ function compact_queue(queue) { if (!item) continue; const obj = item.obj[item.prop]; - if (is_array(obj)) { + if (isArray(obj)) { const compacted = []; for (let j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { @@ -62932,12 +62861,11 @@ function merge(target, source, options = {}) { return target; } if (typeof source !== 'object') { - if (is_array(target)) { + if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || - !has.call(Object.prototype, source)) { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { target[source] = true; } } @@ -62950,13 +62878,13 @@ function merge(target, source, options = {}) { return [target].concat(source); } let mergeTarget = target; - if (is_array(target) && !is_array(source)) { + if (isArray(target) && !isArray(source)) { // @ts-ignore mergeTarget = array_to_object(target, options); } - if (is_array(target) && is_array(source)) { + if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { - if (has.call(target, i)) { + if (has(target, i)) { const targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); @@ -62973,7 +62901,7 @@ function merge(target, source, options = {}) { } return Object.keys(source).reduce(function (acc, key) { const value = source[key]; - if (has.call(acc, key)) { + if (has(acc, key)) { acc[key] = merge(acc[key], value, options); } else { @@ -63097,7 +63025,7 @@ function combine(a, b) { return [].concat(a, b); } function maybe_map(val, fn) { - if (is_array(val)) { + if (values_isArray(val)) { const mapped = []; for (let i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); @@ -63110,7 +63038,7 @@ function maybe_map(val, fn) { ;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs -const stringify_has = Object.prototype.hasOwnProperty; + const array_prefix_generators = { brackets(prefix) { return String(prefix) + '[]'; @@ -63123,12 +63051,10 @@ const array_prefix_generators = { return String(prefix); }, }; -const stringify_is_array = Array.isArray; -const push = Array.prototype.push; const push_to_array = function (arr, value_or_array) { - push.apply(arr, stringify_is_array(value_or_array) ? value_or_array : [value_or_array]); + Array.prototype.push.apply(arr, values_isArray(value_or_array) ? value_or_array : [value_or_array]); }; -const to_ISO = Date.prototype.toISOString; +let toISOString; const defaults = { addQueryPrefix: false, allowDots: false, @@ -63142,11 +63068,11 @@ const defaults = { encoder: encode, encodeValuesOnly: false, format: default_format, - formatter: formatters[default_format], + formatter: default_formatter, /** @deprecated */ indices: false, serializeDate(date) { - return to_ISO.call(date); + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); }, skipNulls: false, strictNullHandling: false, @@ -63186,7 +63112,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al else if (obj instanceof Date) { obj = serializeDate?.(obj); } - else if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { + else if (generateArrayPrefix === 'comma' && values_isArray(obj)) { obj = maybe_map(obj, function (value) { if (value instanceof Date) { return serializeDate?.(value); @@ -63222,7 +63148,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al return values; } let obj_keys; - if (generateArrayPrefix === 'comma' && stringify_is_array(obj)) { + if (generateArrayPrefix === 'comma' && values_isArray(obj)) { // we need to join elements in if (encodeValuesOnly && encoder) { // @ts-expect-error values only @@ -63230,7 +63156,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al } obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } - else if (stringify_is_array(filter)) { + else if (values_isArray(filter)) { obj_keys = filter; } else { @@ -63238,8 +63164,8 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al obj_keys = sort ? keys.sort(sort) : keys; } const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); - const adjusted_prefix = commaRoundTrip && stringify_is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; - if (allowEmptyArrays && stringify_is_array(obj) && obj.length === 0) { + const adjusted_prefix = commaRoundTrip && values_isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; + if (allowEmptyArrays && values_isArray(obj) && obj.length === 0) { return adjusted_prefix + '[]'; } for (let j = 0; j < obj_keys.length; ++j) { @@ -63252,7 +63178,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al } // @ts-ignore const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; - const key_prefix = stringify_is_array(obj) ? + const key_prefix = values_isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix @@ -63262,7 +63188,7 @@ function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, al valueSideChannel.set(sentinel, sideChannel); push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, // @ts-ignore - generateArrayPrefix === 'comma' && encodeValuesOnly && stringify_is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); + generateArrayPrefix === 'comma' && encodeValuesOnly && values_isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); } return values; } @@ -63282,14 +63208,14 @@ function normalize_stringify_options(opts = defaults) { } let format = default_format; if (typeof opts.format !== 'undefined') { - if (!stringify_has.call(formatters, opts.format)) { + if (!has(formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } const formatter = formatters[format]; let filter = defaults.filter; - if (typeof opts.filter === 'function' || stringify_is_array(opts.filter)) { + if (typeof opts.filter === 'function' || values_isArray(opts.filter)) { filter = opts.filter; } let arrayFormat; @@ -63343,7 +63269,7 @@ function stringify(object, opts = {}) { filter = options.filter; obj = filter('', obj); } - else if (stringify_is_array(options.filter)) { + else if (values_isArray(options.filter)) { filter = options.filter; obj_keys = filter; } @@ -63531,7 +63457,90 @@ function findDoubleNewlineIndex(buffer) { return -1; } //# sourceMappingURL=line.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/core/streaming.mjs +var _Stream_client; + + @@ -63540,12 +63549,15 @@ function findDoubleNewlineIndex(buffer) { class Stream { - constructor(iterator, controller) { + constructor(iterator, controller, client) { this.iterator = iterator; + _Stream_client.set(this, void 0); this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); } - static fromSSEResponse(response, controller) { + static fromSSEResponse(response, controller, client) { let consumed = false; + const logger = client ? loggerFor(client) : console; async function* iterator() { if (consumed) { throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); @@ -63560,16 +63572,14 @@ class Stream { done = true; continue; } - if (sse.event === null || - sse.event.startsWith('response.') || - sse.event.startsWith('transcript.')) { + if (sse.event === null || !sse.event.startsWith('thread.')) { let data; try { data = JSON.parse(sse.data); } catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); throw e; } if (data && data.error) { @@ -63608,13 +63618,13 @@ class Stream { controller.abort(); } } - return new Stream(iterator, controller); + return new Stream(iterator, controller, client); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ - static fromReadableStream(readableStream, controller) { + static fromReadableStream(readableStream, controller, client) { let consumed = false; async function* iterLines() { const lineDecoder = new LineDecoder(); @@ -63655,9 +63665,9 @@ class Stream { controller.abort(); } } - return new Stream(iterator, controller); + return new Stream(iterator, controller, client); } - [Symbol.asyncIterator]() { + [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { return this.iterator(); } /** @@ -63681,8 +63691,8 @@ class Stream { }; }; return [ - new Stream(() => teeIterator(left), this.controller), - new Stream(() => teeIterator(right), this.controller), + new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), ]; } /** @@ -63828,9 +63838,9 @@ async function defaultParseResponse(client, props) { // 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 props.options.__streamClass.fromSSEResponse(response, props.controller, client); } - return Stream.fromSSEResponse(response, props.controller); + return Stream.fromSSEResponse(response, props.controller, client); } // fetch refuses to read the body when the status code is 204. if (response.status === 204) { @@ -64104,7 +64114,7 @@ const maybeMultipartFormRequestOptions = async (opts, fetch) => { const multipartFormRequestOptions = async (opts, fetch) => { return { ...opts, body: await createForm(opts.body, fetch) }; }; -const supportsFormDataMap = new WeakMap(); +const supportsFormDataMap = /* @__PURE__ */ new WeakMap(); /** * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". @@ -64305,21 +64315,38 @@ class APIResource { function encodeURIPath(str) { return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } +const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { // If there are no params, no processing is needed. if (statics.length === 1) return statics[0]; let postPath = false; + const invalidSegments = []; const path = statics.reduce((previousValue, currentValue, index) => { if (/[?#]/.test(currentValue)) { postPath = true; } - return (previousValue + - currentValue + - (index === params.length ? '' : (postPath ? encodeURIComponent : pathEncoder)(String(params[index])))); + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); }, ''); const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegments = []; const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; let match; // Find all invalid segments @@ -64327,8 +64354,10 @@ const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(sta invalidSegments.push({ start: match.index, length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, }); } + invalidSegments.sort((a, b) => a.start - b.start); if (invalidSegments.length > 0) { let lastEnd = 0; const underline = invalidSegments.reduce((acc, segment) => { @@ -64337,14 +64366,16 @@ const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(sta lastEnd = segment.start + segment.length; return acc + spaces + arrows; }, ''); - throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${path}\n${underline}`); + throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); } return path; }; /** * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. */ -const path = createPathTagFunction(encodeURIPath); +const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); //# sourceMappingURL=path.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -64374,21 +64405,169 @@ class Messages extends APIResource { ;// CONCATENATED MODULE: ./node_modules/openai/error.mjs //# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs -function isRunnableFunctionWithParse(fn) { - return typeof fn.parse === 'function'; +;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs + +function isChatCompletionFunctionTool(tool) { + return tool !== undefined && 'function' in tool && tool.function !== undefined; } -/** - * 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; +function makeParseableResponseFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + return obj; +} +function parser_makeParseableTextFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + return obj; +} +function isAutoParsableResponseFormat(response_format) { + return response_format?.['$brand'] === 'auto-parseable-response-format'; +} +function parser_makeParseableTool(tool, { parser, callback, }) { + const obj = { ...tool }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + return obj; +} +function isAutoParsableTool(tool) { + return tool?.['$brand'] === 'auto-parseable-tool'; +} +function maybeParseChatCompletion(completion, params) { + if (!params || !hasAutoParseableInput(params)) { + return { + ...completion, + choices: completion.choices.map((choice) => { + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + parsed: null, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls, + } + : undefined), + }, + }; + }), + }; } + return parseChatCompletion(completion, params); } -//# sourceMappingURL=RunnableFunction.mjs.map +function parseChatCompletion(completion, params) { + const choices = completion.choices.map((choice) => { + if (choice.finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + if (choice.finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined, + } + : undefined), + parsed: choice.message.content && !choice.message.refusal ? + parseResponseFormat(params, choice.message.content) + : null, + }, + }; + }); + return { ...completion, choices }; +} +function parseResponseFormat(params, content) { + if (params.response_format?.type !== 'json_schema') { + return null; + } + if (params.response_format?.type === 'json_schema') { + if ('$parseRaw' in params.response_format) { + const response_format = params.response_format; + return response_format.$parseRaw(content); + } + return JSON.parse(content); + } + return null; +} +function parseToolCall(params, toolCall) { + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); // TS doesn't narrow based on isChatCompletionTool + return { + ...toolCall, + function: { + ...toolCall.function, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) + : null, + }, + }; +} +function shouldParseToolCall(params, toolCall) { + if (!params || !('tools' in params) || !params.tools) { + return false; + } + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); + return (isChatCompletionFunctionTool(inputTool) && + (isAutoParsableTool(inputTool) || inputTool?.function.strict || false)); +} +function hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.response_format)) { + return true; + } + return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); +} +function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { + for (const toolCall of toolCalls || []) { + if (toolCall.type !== 'function') { + throw new error_OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); + } + } +} +function validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); + } + if (tool.function.strict !== true) { + throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); + } + } +} +//# sourceMappingURL=parser.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/chatCompletionUtils.mjs const isAssistantMessage = (message) => { return message?.role === 'assistant'; @@ -64587,154 +64766,21 @@ _EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedProm return this._emit('error', new error_OpenAIError(String(error))); }; //# sourceMappingURL=EventStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs - -function makeParseableResponseFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function parser_makeParseableTextFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableResponseFormat(response_format) { - return response_format?.['$brand'] === 'auto-parseable-response-format'; -} -function parser_makeParseableTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function maybeParseChatCompletion(completion, params) { - if (!params || !hasAutoParseableInput(params)) { - return { - ...completion, - choices: completion.choices.map((choice) => ({ - ...choice, - message: { - ...choice.message, - parsed: null, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls, - } - : undefined), - }, - })), - }; - } - return parseChatCompletion(completion, params); -} -function parseChatCompletion(completion, params) { - const choices = completion.choices.map((choice) => { - if (choice.finish_reason === 'length') { - throw new LengthFinishReasonError(); - } - if (choice.finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - return { - ...choice, - message: { - ...choice.message, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? undefined, - } - : undefined), - parsed: choice.message.content && !choice.message.refusal ? - parseResponseFormat(params, choice.message.content) - : null, - }, - }; - }); - return { ...completion, choices }; -} -function parseResponseFormat(params, content) { - if (params.response_format?.type !== 'json_schema') { - return null; - } - if (params.response_format?.type === 'json_schema') { - if ('$parseRaw' in params.response_format) { - const response_format = params.response_format; - return response_format.$parseRaw(content); - } - return JSON.parse(content); - } - return null; -} -function parseToolCall(params, toolCall) { - const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name); - return { - ...toolCall, - function: { - ...toolCall.function, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) - : null, - }, - }; -} -function shouldParseToolCall(params, toolCall) { - if (!params) { - return false; - } - const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name); - return isAutoParsableTool(inputTool) || inputTool?.function.strict || false; -} -function hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.response_format)) { - return true; - } - return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); +;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; } -function validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; } } -//# sourceMappingURL=parser.mjs.map +//# sourceMappingURL=RunnableFunction.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; @@ -64865,7 +64911,7 @@ class AbstractChatCompletionRunner extends EventStream { async _runTools(client, params, options) { const role = 'tool'; const { tool_choice = 'auto', stream, ...restParams } = params; - const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name; const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; // TODO(someday): clean this logic up const inputTools = params.tools.map((tool) => { @@ -64983,7 +65029,7 @@ _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletion for (let i = this.messages.length - 1; i >= 0; i--) { const message = this.messages[i]; if (isAssistantMessage(message) && message?.tool_calls?.length) { - return message.tool_calls.at(-1)?.function; + return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function; } } return; @@ -65044,9 +65090,6 @@ class ChatCompletionRunner extends AbstractChatCompletionRunner { } } //# sourceMappingURL=ChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs - -//# sourceMappingURL=streaming.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs const STR = 0b000000001; const NUM = 0b000000010; @@ -65289,6 +65332,9 @@ const _parseJSON = (jsonString, allow) => { const partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); //# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs + +//# sourceMappingURL=streaming.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; @@ -65476,7 +65522,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner { throw new Error('tool call snapshot missing `type`'); } if (toolCallSnapshot.type === 'function') { - const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name); + const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); // TS doesn't narrow based on isChatCompletionTool this._emit('tool_calls.function.arguments.done', { name: toolCallSnapshot.function.name, index: toolCallIndex, @@ -65933,8 +65979,8 @@ Chat.Completions = Completions; //# sourceMappingURL=index.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/internal/headers.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const brand_privateNullableHeaders = Symbol('brand.privateNullableHeaders'); -const isArray = Array.isArray; + +const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders'); function* iterateHeaders(headers) { if (!headers) return; @@ -65951,7 +65997,7 @@ function* iterateHeaders(headers) { if (headers instanceof Headers) { iter = headers.entries(); } - else if (isArray(headers)) { + else if (isReadonlyArray(headers)) { iter = headers; } else { @@ -65962,7 +66008,7 @@ function* iterateHeaders(headers) { const name = row[0]; if (typeof name !== 'string') throw new TypeError('expected header name to be a string'); - const values = isArray(row[1]) ? row[1] : [row[1]]; + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; let didClear = false; for (const value of values) { if (value === undefined) @@ -67895,7 +67941,7 @@ class Jobs extends APIResource { * Response includes details of the enqueued job including job status and the name * of the fine-tuned models once complete. * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) * * @example * ```ts @@ -67911,7 +67957,7 @@ class Jobs extends APIResource { /** * Get info about a fine-tuning job. * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) * * @example * ```ts @@ -68057,34 +68103,11 @@ class Images extends APIResource { createVariation(body, options) { return this._client.post('/images/variations', multipartFormRequestOptions({ body, ...options }, this._client)); } - /** - * Creates an edited or extended image given one or more source images and a - * prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.edit({ - * image: fs.createReadStream('path/to/file'), - * prompt: 'A cute baby sea otter wearing a beret', - * }); - * ``` - */ edit(body, options) { - return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options }, this._client)); + return this._client.post('/images/edits', multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client)); } - /** - * Creates an image given a prompt. - * [Learn more](https://platform.openai.com/docs/guides/images). - * - * @example - * ```ts - * const imagesResponse = await client.images.generate({ - * prompt: 'A cute baby sea otter', - * }); - * ``` - */ generate(body, options) { - return this._client.post('/images/generations', { body, ...options }); + return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false }); } } //# sourceMappingURL=images.mjs.map @@ -68579,6 +68602,11 @@ class Responses extends APIResource { query, ...options, stream: query?.stream ?? false, + })._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp); + } + return rsp; }); } /** @@ -69084,6 +69112,104 @@ class VectorStores extends APIResource { VectorStores.Files = vector_stores_files_Files; VectorStores.FileBatches = FileBatches; //# sourceMappingURL=vector-stores.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/webhooks.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader; + + + + +class Webhooks extends APIResource { + constructor() { + super(...arguments); + _Webhooks_instances.add(this); + } + /** + * Validates that the given payload was sent by OpenAI and parses the payload. + */ + async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + await this.verifySignature(payload, headers, secret, tolerance); + return JSON.parse(payload); + } + /** + * Validates whether or not the webhook payload was sent by OpenAI. + * + * An error will be raised if the webhook payload was not sent by OpenAI. + * + * @param payload - The webhook payload + * @param headers - The webhook headers + * @param secret - The webhook secret (optional, will use client secret if not provided) + * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) + */ + async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + if (typeof crypto === 'undefined' || + typeof crypto.subtle.importKey !== 'function' || + typeof crypto.subtle.verify !== 'function') { + throw new Error('Webhook signature verification is only supported when the `crypto` global is defined'); + } + __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); + const headersObj = buildHeaders([headers]).values; + const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-signature'); + const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-timestamp'); + const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-id'); + // Validate timestamp to prevent replay attacks + const timestampSeconds = parseInt(timestamp, 10); + if (isNaN(timestampSeconds)) { + throw new InvalidWebhookSignatureError('Invalid webhook timestamp format'); + } + const nowSeconds = Math.floor(Date.now() / 1000); + if (nowSeconds - timestampSeconds > tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too old'); + } + if (timestampSeconds > nowSeconds + tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too new'); + } + // Extract signatures from v1, format + // The signature header can have multiple values, separated by spaces. + // Each value is in the format v1,. We should accept if any match. + const signatures = signatureHeader + .split(' ') + .map((part) => (part.startsWith('v1,') ? part.substring(3) : part)); + // Decode the secret if it starts with whsec_ + const decodedSecret = secret.startsWith('whsec_') ? + Buffer.from(secret.replace('whsec_', ''), 'base64') + : Buffer.from(secret, 'utf-8'); + // Create the signed payload: {webhook_id}.{timestamp}.{payload} + const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + // Import the secret as a cryptographic key for HMAC + const key = await crypto.subtle.importKey('raw', decodedSecret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']); + // Check if any signature matches using timing-safe WebCrypto verify + for (const signature of signatures) { + try { + const signatureBytes = Buffer.from(signature, 'base64'); + const isValid = await crypto.subtle.verify('HMAC', key, signatureBytes, new TextEncoder().encode(signedPayload)); + if (isValid) { + return; // Valid signature found + } + } + catch { + // Invalid base64 or signature format, continue to next signature + continue; + } + } + throw new InvalidWebhookSignatureError('The given webhook signature does not match the expected signature'); + } +} +_Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) { + if (typeof secret !== 'string' || secret.length === 0) { + throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); + } +}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) { + if (!headers) { + throw new Error(`Headers are required`); + } + const value = headers.get(name); + if (value === null || value === undefined) { + throw new Error(`Missing required header: ${name}`); + } + return value; +}; +//# sourceMappingURL=webhooks.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -69104,10 +69230,11 @@ VectorStores.FileBatches = FileBatches; + //# sourceMappingURL=index.mjs.map ;// CONCATENATED MODULE: ./node_modules/openai/client.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var client_a, _OpenAI_encoder; +var _OpenAI_instances, client_a, _OpenAI_encoder, _OpenAI_baseURLOverridden; @@ -69156,6 +69283,7 @@ class OpenAI { * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] + * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. @@ -69165,7 +69293,8 @@ class OpenAI { * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ - constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) { + constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) { + _OpenAI_instances.add(this); _OpenAI_encoder.set(this, void 0); this.completions = new completions_Completions(this); this.chat = new Chat(this); @@ -69178,6 +69307,7 @@ class OpenAI { this.fineTuning = new FineTuning(this); this.graders = new graders_Graders(this); this.vectorStores = new VectorStores(this); + this.webhooks = new Webhooks(this); this.beta = new Beta(this); this.batches = new Batches(this); this.uploads = new Uploads(this); @@ -69191,6 +69321,7 @@ class OpenAI { apiKey, organization, project, + webhookSecret, ...opts, baseURL: baseURL || `https://api.openai.com/v1`, }; @@ -69215,24 +69346,28 @@ class OpenAI { this.apiKey = apiKey; this.organization = organization; this.project = project; + this.webhookSecret = webhookSecret; } /** * Create a new client instance re-using the same options given to the current client with optional overriding. */ withOptions(options) { - return new this.constructor({ + const client = new this.constructor({ ...this._options, baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, + fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, organization: this.organization, project: this.project, + webhookSecret: this.webhookSecret, ...options, }); + return client; } defaultQuery() { return this._options.defaultQuery; @@ -69240,7 +69375,7 @@ class OpenAI { validateHeaders({ values, nulls }) { return; } - authHeaders(opts) { + async authHeaders(opts) { return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); } stringifyQuery(query) { @@ -69255,10 +69390,11 @@ class OpenAI { makeStatusError(status, error, message, headers) { return APIError.generate(status, error, message, headers); } - buildURL(path, query) { + buildURL(path, query, defaultBaseURL) { + const baseURL = (!__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; const url = isAbsoluteURL(path) ? new URL(path) - : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); const defaultQuery = this.defaultQuery(); if (!isEmptyObj(defaultQuery)) { query = { ...defaultQuery, ...query }; @@ -69309,7 +69445,9 @@ class OpenAI { retriesRemaining = maxRetries; } await this.prepareOptions(options); - const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); await this.prepareRequest(req, { url, options }); /** Not an API request ID, just for correlating local log entries. */ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); @@ -69367,7 +69505,7 @@ class OpenAI { .join(''); const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; if (!response.ok) { - const shouldRetry = this.shouldRetry(response); + const shouldRetry = await this.shouldRetry(response); if (retriesRemaining && shouldRetry) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; // We don't need the body of this response. @@ -69441,7 +69579,7 @@ class OpenAI { clearTimeout(timeout); } } - shouldRetry(response) { + async shouldRetry(response) { // Note this is not a standard header. const shouldRetryHeader = response.headers.get('x-should-retry'); // If the server explicitly says whether or not to retry, obey. @@ -69503,15 +69641,15 @@ class OpenAI { const jitter = 1 - Math.random() * 0.25; return sleepSeconds * jitter * 1000; } - buildRequest(inputOptions, { retryCount = 0 } = {}) { + async buildRequest(inputOptions, { retryCount = 0 } = {}) { const options = { ...inputOptions }; - const { method, path, query } = options; - const url = this.buildURL(path, query); + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); if ('timeout' in options) validatePositiveInteger('timeout', options.timeout); options.timeout = options.timeout ?? this.timeout; const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); const req = { method, headers: reqHeaders, @@ -69524,7 +69662,7 @@ class OpenAI { }; return { req, url, timeout: options.timeout }; } - buildHeaders({ options, method, bodyHeaders, retryCount, }) { + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { let idempotencyHeaders = {}; if (this.idempotencyHeader && method !== 'get') { if (!options.idempotencyKey) @@ -69542,7 +69680,7 @@ class OpenAI { 'OpenAI-Organization': this.organization, 'OpenAI-Project': this.project, }, - this.authHeaders(options), + await this.authHeaders(options), this._options.defaultHeaders, bodyHeaders, options.headers, @@ -69583,7 +69721,9 @@ class OpenAI { } } } -client_a = OpenAI, _OpenAI_encoder = new WeakMap(); +client_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() { + return this.baseURL !== 'https://api.openai.com/v1'; +}; OpenAI.OpenAI = client_a; OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes OpenAI.OpenAIError = error_OpenAIError; @@ -69599,6 +69739,7 @@ OpenAI.AuthenticationError = AuthenticationError; OpenAI.InternalServerError = InternalServerError; OpenAI.PermissionDeniedError = PermissionDeniedError; OpenAI.UnprocessableEntityError = UnprocessableEntityError; +OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; OpenAI.toFile = toFile; OpenAI.Completions = completions_Completions; OpenAI.Chat = Chat; @@ -69611,6 +69752,7 @@ OpenAI.Models = Models; OpenAI.FineTuning = FineTuning; OpenAI.Graders = graders_Graders; OpenAI.VectorStores = VectorStores; +OpenAI.Webhooks = Webhooks; OpenAI.Beta = Beta; OpenAI.Batches = Batches; OpenAI.Uploads = Uploads; @@ -69683,7 +69825,7 @@ class AzureOpenAI extends OpenAI { this.apiVersion = apiVersion; this.deploymentName = deployment; } - buildRequest(options, props = {}) { + async buildRequest(options, props = {}) { if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { if (!isObj(options.body)) { throw new Error('Expected request body to be an object'); @@ -69705,7 +69847,7 @@ class AzureOpenAI extends OpenAI { } return undefined; } - authHeaders(opts) { + async authHeaders(opts) { return; } async prepareOptions(opts) { @@ -69934,6 +70076,8 @@ const values_startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; const values_isAbsoluteURL = (url) => { return values_startsWithSchemeRegexp.test(url); }; +let utils_values_isArray = (val) => ((utils_values_isArray = Array.isArray), utils_values_isArray(val)); +let values_isReadonlyArray = utils_values_isArray; /** Returns an object if the given value isn't an object, otherwise returns as-is */ function values_maybeObj(x) { if (typeof x !== 'object') { @@ -70023,89 +70167,8 @@ const values_safeJSON = (text) => { // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); //# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/log.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const log_levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const log_parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; - } - if (values_hasOwn(log_levelNumbers, maybeLevel)) { - return maybeLevel; - } - log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); - return undefined; -}; -function log_noop() { } -function log_makeLogFn(fnLevel, logger, logLevel) { - if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { - return log_noop; - } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); - } -} -const log_noopLogger = { - error: log_noop, - warn: log_noop, - info: log_noop, - debug: log_noop, -}; -let log_cachedLoggers = new WeakMap(); -function log_loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return log_noopLogger; - } - const cachedLogger = log_cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: log_makeLogFn('error', logger, logLevel), - warn: log_makeLogFn('warn', logger, logLevel), - info: log_makeLogFn('info', logger, logLevel), - debug: log_makeLogFn('debug', logger, logLevel), - }; - log_cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -const log_formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'x-api-key' || - name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); - } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; - } - delete details.retryOfRequestLogID; - } - return details; -}; -//# sourceMappingURL=log.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/version.mjs -const version_VERSION = '0.54.0'; // x-release-please-version +const version_VERSION = '0.59.0'; // x-release-please-version //# sourceMappingURL=version.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -70498,7 +70561,91 @@ function line_findDoubleNewlineIndex(buffer) { return -1; } //# sourceMappingURL=line.mjs.map +;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const log_levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const log_parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (values_hasOwn(log_levelNumbers, maybeLevel)) { + return maybeLevel; + } + log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); + return undefined; +}; +function log_noop() { } +function log_makeLogFn(fnLevel, logger, logLevel) { + if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { + return log_noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const log_noopLogger = { + error: log_noop, + warn: log_noop, + info: log_noop, + debug: log_noop, +}; +let log_cachedLoggers = /* @__PURE__ */ new WeakMap(); +function log_loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return log_noopLogger; + } + const cachedLogger = log_cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: log_makeLogFn('error', logger, logLevel), + warn: log_makeLogFn('warn', logger, logLevel), + info: log_makeLogFn('info', logger, logLevel), + debug: log_makeLogFn('debug', logger, logLevel), + }; + log_cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +const log_formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'x-api-key' || + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/core/streaming.mjs +var streaming_Stream_client; + + @@ -70508,12 +70655,15 @@ function line_findDoubleNewlineIndex(buffer) { class streaming_Stream { - constructor(iterator, controller) { + constructor(iterator, controller, client) { this.iterator = iterator; + streaming_Stream_client.set(this, void 0); this.controller = controller; + tslib_classPrivateFieldSet(this, streaming_Stream_client, client, "f"); } - static fromSSEResponse(response, controller) { + static fromSSEResponse(response, controller, client) { let consumed = false; + const logger = client ? log_loggerFor(client) : console; async function* iterator() { if (consumed) { throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); @@ -70527,8 +70677,8 @@ class streaming_Stream { yield JSON.parse(sse.data); } catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); throw e; } } @@ -70542,8 +70692,8 @@ class streaming_Stream { yield JSON.parse(sse.data); } catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); throw e; } } @@ -70568,13 +70718,13 @@ class streaming_Stream { controller.abort(); } } - return new streaming_Stream(iterator, controller); + return new streaming_Stream(iterator, controller, client); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ - static fromReadableStream(readableStream, controller) { + static fromReadableStream(readableStream, controller, client) { let consumed = false; async function* iterLines() { const lineDecoder = new line_LineDecoder(); @@ -70615,9 +70765,9 @@ class streaming_Stream { controller.abort(); } } - return new streaming_Stream(iterator, controller); + return new streaming_Stream(iterator, controller, client); } - [Symbol.asyncIterator]() { + [(streaming_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { return this.iterator(); } /** @@ -70641,8 +70791,8 @@ class streaming_Stream { }; }; return [ - new streaming_Stream(() => teeIterator(left), this.controller), - new streaming_Stream(() => teeIterator(right), this.controller), + new streaming_Stream(() => teeIterator(left), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), + new streaming_Stream(() => teeIterator(right), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), ]; } /** @@ -71063,7 +71213,7 @@ const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { const uploads_multipartFormRequestOptions = async (opts, fetch) => { return { ...opts, body: await uploads_createForm(opts.body, fetch) }; }; -const uploads_supportsFormDataMap = new WeakMap(); +const uploads_supportsFormDataMap = /* @__PURE__ */ new WeakMap(); /** * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". @@ -71263,8 +71413,8 @@ class resource_APIResource { //# sourceMappingURL=resource.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/internal/headers.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + const headers_brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); -const headers_isArray = Array.isArray; function* headers_iterateHeaders(headers) { if (!headers) return; @@ -71281,7 +71431,7 @@ function* headers_iterateHeaders(headers) { if (headers instanceof Headers) { iter = headers.entries(); } - else if (headers_isArray(headers)) { + else if (values_isReadonlyArray(headers)) { iter = headers; } else { @@ -71292,7 +71442,7 @@ function* headers_iterateHeaders(headers) { const name = row[0]; if (typeof name !== 'string') throw new TypeError('expected header name to be a string'); - const values = headers_isArray(row[1]) ? row[1] : [row[1]]; + const values = values_isReadonlyArray(row[1]) ? row[1] : [row[1]]; let didClear = false; for (const value of values) { if (value === undefined) @@ -71349,21 +71499,38 @@ const headers_isEmptyHeaders = (headers) => { function path_encodeURIPath(str) { return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); } +const path_EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => function path(statics, ...params) { // If there are no params, no processing is needed. if (statics.length === 1) return statics[0]; let postPath = false; + const invalidSegments = []; const path = statics.reduce((previousValue, currentValue, index) => { if (/[?#]/.test(currentValue)) { postPath = true; } - return (previousValue + - currentValue + - (index === params.length ? '' : (postPath ? encodeURIComponent : pathEncoder)(String(params[index])))); + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? path_EMPTY) ?? path_EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); }, ''); const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegments = []; const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; let match; // Find all invalid segments @@ -71371,8 +71538,10 @@ const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => functio invalidSegments.push({ start: match.index, length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, }); } + invalidSegments.sort((a, b) => a.start - b.start); if (invalidSegments.length > 0) { let lastEnd = 0; const underline = invalidSegments.reduce((acc, segment) => { @@ -71381,14 +71550,16 @@ const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => functio lastEnd = segment.start + segment.length; return acc + spaces + arrows; }, ''); - throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${path}\n${underline}`); + throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); } return path; }; /** * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. */ -const path_path = path_createPathTagFunction(path_encodeURIPath); +const path_path = /* @__PURE__ */ path_createPathTagFunction(path_encodeURIPath); //# sourceMappingURL=path.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/files.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. @@ -71636,7 +71807,7 @@ class batches_Batches extends resource_APIResource { * messages: [ * { content: 'Hello, world', role: 'user' }, * ], - * model: 'claude-3-7-sonnet-20250219', + * model: 'claude-sonnet-4-20250514', * }, * }, * ], @@ -72163,23 +72334,32 @@ class BetaMessageStream { } async _createMessage(messages, params, options) { const signal = options?.signal; + let abortHandler; if (signal) { if (signal.aborted) this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + try { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); } _connected(response) { if (this.ended) @@ -72330,21 +72510,30 @@ class BetaMessageStream { } async _fromReadableStream(readableStream, options) { const signal = options?.signal; + let abortHandler; if (signal) { if (signal.aborted) this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - this._connected(null); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + try { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } } - tslib_classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); } [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { if (this.receivedMessages.length === 0) { @@ -72478,14 +72667,19 @@ class BetaMessageStream { switch (event.delta.type) { case 'text_delta': { if (snapshotContent?.type === 'text') { - snapshotContent.text += event.delta.text; + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; } break; } case 'citations_delta': { if (snapshotContent?.type === 'text') { - snapshotContent.citations ?? (snapshotContent.citations = []); - snapshotContent.citations.push(event.delta.citation); + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; } break; } @@ -72496,32 +72690,40 @@ class BetaMessageStream { // non-enumerable property on the snapshot let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; jsonBuf += event.delta.partial_json; - Object.defineProperty(snapshotContent, JSON_BUF_PROPERTY, { + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { value: jsonBuf, enumerable: false, writable: true, }); if (jsonBuf) { try { - snapshotContent.input = parser_partialParse(jsonBuf); + newContent.input = parser_partialParse(jsonBuf); } catch (err) { const error = new error_AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); tslib_classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); } } + snapshot.content[event.index] = newContent; } break; } case 'thinking_delta': { if (snapshotContent?.type === 'thinking') { - snapshotContent.thinking += event.delta.thinking; + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; } break; } case 'signature_delta': { if (snapshotContent?.type === 'thinking') { - snapshotContent.signature = event.delta.signature; + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; } break; } @@ -72603,6 +72805,9 @@ const MODEL_NONSTREAMING_TOKENS = { 'claude-4-opus-20250514': 8192, 'anthropic.claude-opus-4-20250514-v1:0': 8192, 'claude-opus-4@20250514': 8192, + 'claude-opus-4-1-20250805': 8192, + 'anthropic.claude-opus-4-1-20250805-v1:0': 8192, + 'claude-opus-4-1@20250805': 8192, }; //# sourceMappingURL=constants.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs @@ -72619,6 +72824,7 @@ const DEPRECATED_MODELS = { 'claude-instant-1.1-100k': 'November 6th, 2024', 'claude-instant-1.2': 'November 6th, 2024', 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', 'claude-2.1': 'July 21st, 2025', 'claude-2.0': 'July 21st, 2025', }; @@ -72858,23 +73064,32 @@ class MessageStream { } async _createMessage(messages, params, options) { const signal = options?.signal; + let abortHandler; if (signal) { if (signal.aborted) this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + try { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); } _connected(response) { if (this.ended) @@ -73025,21 +73240,30 @@ class MessageStream { } async _fromReadableStream(readableStream, options) { const signal = options?.signal; + let abortHandler; if (signal) { if (signal.aborted) this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - this._connected(null); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + try { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } } - tslib_classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); } [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { if (this.receivedMessages.length === 0) { @@ -73166,21 +73390,26 @@ class MessageStream { } return snapshot; case 'content_block_start': - snapshot.content.push(event.content_block); + snapshot.content.push({ ...event.content_block }); return snapshot; case 'content_block_delta': { const snapshotContent = snapshot.content.at(event.index); switch (event.delta.type) { case 'text_delta': { if (snapshotContent?.type === 'text') { - snapshotContent.text += event.delta.text; + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; } break; } case 'citations_delta': { if (snapshotContent?.type === 'text') { - snapshotContent.citations ?? (snapshotContent.citations = []); - snapshotContent.citations.push(event.delta.citation); + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; } break; } @@ -73191,26 +73420,34 @@ class MessageStream { // non-enumerable property on the snapshot let jsonBuf = snapshotContent[MessageStream_JSON_BUF_PROPERTY] || ''; jsonBuf += event.delta.partial_json; - Object.defineProperty(snapshotContent, MessageStream_JSON_BUF_PROPERTY, { + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, MessageStream_JSON_BUF_PROPERTY, { value: jsonBuf, enumerable: false, writable: true, }); if (jsonBuf) { - snapshotContent.input = parser_partialParse(jsonBuf); + newContent.input = parser_partialParse(jsonBuf); } + snapshot.content[event.index] = newContent; } break; } case 'thinking_delta': { if (snapshotContent?.type === 'thinking') { - snapshotContent.thinking += event.delta.thinking; + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; } break; } case 'signature_delta': { if (snapshotContent?.type === 'thinking') { - snapshotContent.signature = event.delta.signature; + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; } break; } @@ -73311,7 +73548,7 @@ class messages_batches_Batches extends resource_APIResource { * messages: [ * { content: 'Hello, world', role: 'user' }, * ], - * model: 'claude-3-7-sonnet-20250219', + * model: 'claude-sonnet-4-20250514', * }, * }, * ], @@ -73494,6 +73731,7 @@ const messages_DEPRECATED_MODELS = { 'claude-instant-1.1-100k': 'November 6th, 2024', 'claude-instant-1.2': 'November 6th, 2024', 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', 'claude-2.1': 'July 21st, 2025', 'claude-2.0': 'July 21st, 2025', }; @@ -73570,8 +73808,7 @@ const env_readEnv = (env) => { //# sourceMappingURL=env.mjs.map ;// CONCATENATED MODULE: ./node_modules/@anthropic-ai/sdk/client.mjs // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var sdk_client_a, _BaseAnthropic_encoder; - +var _BaseAnthropic_instances, sdk_client_a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden; @@ -73595,6 +73832,9 @@ var sdk_client_a, _BaseAnthropic_encoder; +/** + * Base class for Anthropic API clients. + */ class BaseAnthropic { /** * API Client for interfacing with the Anthropic API. @@ -73611,6 +73851,7 @@ class BaseAnthropic { * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ constructor({ baseURL = env_readEnv('ANTHROPIC_BASE_URL'), apiKey = env_readEnv('ANTHROPIC_API_KEY') ?? null, authToken = env_readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); _BaseAnthropic_encoder.set(this, void 0); const options = { apiKey, @@ -73622,7 +73863,7 @@ class BaseAnthropic { throw new error_AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); } this.baseURL = options.baseURL; - this.timeout = options.timeout ?? Anthropic.DEFAULT_TIMEOUT /* 10 minutes */; + this.timeout = options.timeout ?? sdk_client_a.DEFAULT_TIMEOUT /* 10 minutes */; this.logger = options.logger ?? console; const defaultLogLevel = 'warn'; // Set default logLevel early so that we can log a warning in parseLogLevel. @@ -73643,18 +73884,20 @@ class BaseAnthropic { * Create a new client instance re-using the same options given to the current client with optional overriding. */ withOptions(options) { - return new this.constructor({ + const client = new this.constructor({ ...this._options, baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, + fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, authToken: this.authToken, ...options, }); + return client; } defaultQuery() { return this._options.defaultQuery; @@ -73674,16 +73917,16 @@ class BaseAnthropic { } throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); } - authHeaders(opts) { - return headers_buildHeaders([this.apiKeyAuth(opts), this.bearerAuth(opts)]); + async authHeaders(opts) { + return headers_buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); } - apiKeyAuth(opts) { + async apiKeyAuth(opts) { if (this.apiKey == null) { return undefined; } return headers_buildHeaders([{ 'X-Api-Key': this.apiKey }]); } - bearerAuth(opts) { + async bearerAuth(opts) { if (this.authToken == null) { return undefined; } @@ -73715,10 +73958,11 @@ class BaseAnthropic { makeStatusError(status, error, message, headers) { return error_APIError.generate(status, error, message, headers); } - buildURL(path, query) { + buildURL(path, query, defaultBaseURL) { + const baseURL = (!tslib_classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; const url = values_isAbsoluteURL(path) ? new URL(path) - : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); const defaultQuery = this.defaultQuery(); if (!values_isEmptyObj(defaultQuery)) { query = { ...defaultQuery, ...query }; @@ -73732,7 +73976,7 @@ class BaseAnthropic { const defaultTimeout = 10 * 60; const expectedTimeout = (60 * 60 * maxTokens) / 128000; if (expectedTimeout > defaultTimeout) { - throw new error_AnthropicError('Streaming is strongly recommended for operations that may take longer than 10 minutes. ' + + throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' + 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); } return defaultTimeout * 1000; @@ -73778,7 +74022,9 @@ class BaseAnthropic { retriesRemaining = maxRetries; } await this.prepareOptions(options); - const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining }); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); await this.prepareRequest(req, { url, options }); /** Not an API request ID, just for correlating local log entries. */ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); @@ -73836,7 +74082,7 @@ class BaseAnthropic { .join(''); const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; if (!response.ok) { - const shouldRetry = this.shouldRetry(response); + const shouldRetry = await this.shouldRetry(response); if (retriesRemaining && shouldRetry) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; // We don't need the body of this response. @@ -73910,7 +74156,7 @@ class BaseAnthropic { clearTimeout(timeout); } } - shouldRetry(response) { + async shouldRetry(response) { // Note this is not a standard header. const shouldRetryHeader = response.headers.get('x-should-retry'); // If the server explicitly says whether or not to retry, obey. @@ -73977,19 +74223,19 @@ class BaseAnthropic { const defaultTime = 60 * 10 * 1000; // 10 minutes const expectedTime = (maxTime * maxTokens) / 128000; if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { - throw new error_AnthropicError('Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); + throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); } return defaultTime; } - buildRequest(inputOptions, { retryCount = 0 } = {}) { + async buildRequest(inputOptions, { retryCount = 0 } = {}) { const options = { ...inputOptions }; - const { method, path, query } = options; - const url = this.buildURL(path, query); + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); if ('timeout' in options) values_validatePositiveInteger('timeout', options.timeout); options.timeout = options.timeout ?? this.timeout; const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); const req = { method, headers: reqHeaders, @@ -74002,7 +74248,7 @@ class BaseAnthropic { }; return { req, url, timeout: options.timeout }; } - buildHeaders({ options, method, bodyHeaders, retryCount, }) { + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { let idempotencyHeaders = {}; if (this.idempotencyHeader && method !== 'get') { if (!options.idempotencyKey) @@ -74022,7 +74268,7 @@ class BaseAnthropic { : undefined), 'anthropic-version': '2023-06-01', }, - this.authHeaders(options), + await this.authHeaders(options), this._options.defaultHeaders, bodyHeaders, options.headers, @@ -74063,7 +74309,9 @@ class BaseAnthropic { } } } -sdk_client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(); +sdk_client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { + return this.baseURL !== 'https://api.anthropic.com'; +}; BaseAnthropic.Anthropic = sdk_client_a; BaseAnthropic.HUMAN_PROMPT = '\n\nHuman:'; BaseAnthropic.AI_PROMPT = '\n\nAssistant:'; @@ -74123,7 +74371,7 @@ const v6ToV1 = dist/* v6ToV1 */.JE; const v7 = dist.v7; const NIL = dist/* NIL */.wD; const MAX = dist/* MAX */.Zu; -const wrapper_version = dist/* version */.rE; +const version = dist/* version */.rE; const wrapper_validate = dist/* validate */.tf; const wrapper_stringify = dist/* stringify */.As; const wrapper_parse = dist/* parse */.qg; @@ -74785,7 +75033,7 @@ class BaseMessage extends Serializable { writable: true, value: void 0 }); - /** Response metadata. For example: response headers, logprobs, token counts. */ + /** Response metadata. For example: response headers, logprobs, token counts, model name. */ Object.defineProperty(this, "response_metadata", { enumerable: true, configurable: true, @@ -75024,6 +75272,12 @@ class tool_ToolMessage extends BaseMessage { writable: true, value: void 0 }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); /** * Artifact of the Tool execution which is not meant to be sent to the model. * @@ -75041,6 +75295,7 @@ class tool_ToolMessage extends BaseMessage { this.tool_call_id = fields.tool_call_id; this.artifact = fields.artifact; this.status = fields.status; + this.metadata = fields.metadata; } _getType() { return "tool"; @@ -75301,29 +75556,42 @@ class ai_AIMessageChunk extends BaseMessageChunk { }; } else { + const groupedToolCallChunk = fields.tool_call_chunks.reduce((acc, chunk) => { + // Assign a fallback ID if the chunk doesn't have one + // This can happen with tools that have empty schemas + const chunkId = chunk.id || `fallback-${chunk.index || 0}`; + acc[chunkId] = acc[chunkId] ?? []; + acc[chunkId].push(chunk); + return acc; + }, {}); const toolCalls = []; const invalidToolCalls = []; - for (const toolCallChunk of fields.tool_call_chunks) { + for (const [id, chunks] of Object.entries(groupedToolCallChunk)) { let parsedArgs = {}; + const name = chunks[0]?.name ?? ""; + const joinedArgs = chunks.map((c) => c.args || "").join(""); + const argsStr = joinedArgs.length ? joinedArgs : "{}"; + // Use the original ID from the first chunk if it exists, otherwise use the grouped ID + const originalId = chunks[0]?.id || id; try { - parsedArgs = parsePartialJson(toolCallChunk.args || "{}"); + parsedArgs = parsePartialJson(argsStr); if (parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) { throw new Error("Malformed tool call chunk args."); } toolCalls.push({ - name: toolCallChunk.name ?? "", + name, args: parsedArgs, - id: toolCallChunk.id, + id: originalId, type: "tool_call", }); } catch (e) { invalidToolCalls.push({ - name: toolCallChunk.name, - args: toolCallChunk.args, - id: toolCallChunk.id, + name, + args: argsStr, + id: originalId, error: "Malformed args.", type: "invalid_tool_call", }); @@ -80270,5759 +80538,6856 @@ const NEVER = INVALID; // EXTERNAL MODULE: ./node_modules/p-retry/index.js var p_retry = __nccwpck_require__(2103); -// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js -var p_queue_dist = __nccwpck_require__(6459); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js +class MockAsyncLocalStorage { + getStore() { + return undefined; + } + run(_, callback) { + return callback(); + } +} +const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const mockAsyncLocalStorage = new MockAsyncLocalStorage(); +class AsyncLocalStorageProvider { + getInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; + } + initializeGlobalInstance(instance) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[TRACING_ALS_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[TRACING_ALS_KEY] = instance; + } + } +} +const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); +function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); + if (!permitAbsentRunTree && runTree === undefined) { + throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); + } + return runTree; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function withRunTree(runTree, fn) { + const storage = AsyncLocalStorageProviderSingleton.getInstance(); + return new Promise((resolve, reject) => { + storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); + }); +} +const ROOT = Symbol.for("langsmith:traceable:root"); +function isTraceableFunction(x +// eslint-disable-next-line @typescript-eslint/no-explicit-any +) { + return typeof x === "function" && "langsmith:traceable" in x; +} -// Wrap the default fetch call due to issues with illegal invocations -// in some environments: -// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err -// @ts-expect-error Broad typing to support a range of fetch implementations -const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); -const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); +;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + */ +const _hasOwnProperty = Object.prototype.hasOwnProperty; +function helpers_hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys = new Array(obj.length); + for (let k = 0; k < keys.length; k++) { + keys[k] = "" + k; + } + return keys; + } + if (Object.keys) { + return Object.keys(obj); + } + let keys = []; + for (let i in obj) { + if (helpers_hasOwnProperty(obj, i)) { + keys.push(i); + } + } + return keys; +} /** - * Overrides the fetch implementation used for LangSmith calls. - * You should use this if you need to use an implementation of fetch - * other than the default global (e.g. for dealing with proxies). - * @param fetch The new fetch functino to use. + * Deeply clone the object. + * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) + * @param {any} obj value to clone + * @return {any} cloned obj */ -const overrideFetchImplementation = (fetch) => { - globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; -}; -const _globalFetchImplementationIsNodeFetch = () => { - const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; - if (!fetchImpl) +function helpers_deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; //this is how JSON.stringify behaves for array items + default: + return obj; //no need to clone primitives + } +} +//3x faster than cached /^\d+$/.test(str) +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; + } return false; - // Check if the implementation has node-fetch specific properties - return (typeof fetchImpl === "function" && - "Headers" in fetchImpl && - "Request" in fetchImpl && - "Response" in fetchImpl); -}; + } + return true; +} /** - * @internal + * Escapes a json pointer path + * @param path The raw pointer + * @return the Escaped path */ -const _getFetchImplementation = (debug) => { - return async (...args) => { - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - const [url, options] = args; - console.log(`→ ${options?.method || "GET"} ${url}`); - } - const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? - DEFAULT_FETCH_IMPLEMENTATION)(...args); - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - console.log(`← ${res.status} ${res.statusText} ${res.url}`); +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) + return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +/** + * Unescapes a json pointer path + * @param path The escaped pointer + * @return The unescaped path + */ +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +function _getPathRecursive(root, obj) { + let found; + for (let key in root) { + if (helpers_hasOwnProperty(root, key)) { + if (root[key] === obj) { + return escapePathComponent(key) + "/"; + } + else if (typeof root[key] === "object") { + found = _getPathRecursive(root[key], obj); + if (found != "") { + return escapePathComponent(key) + "/" + found; + } + } } - return res; - }; -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js - - - -const STATUS_NO_RETRY = [ - 400, // Bad Request - 401, // Unauthorized - 403, // Forbidden - 404, // Not Found - 405, // Method Not Allowed - 406, // Not Acceptable - 407, // Proxy Authentication Required - 408, // Request Timeout -]; -const STATUS_IGNORE = [ - 409, // Conflict -]; + } + return ""; +} +function getPath(root, obj) { + if (root === obj) { + return "/"; + } + const path = _getPathRecursive(root, obj); + if (path === "") { + throw new Error("Object not found in root"); + } + return `/${path}`; +} /** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. + * Recursively checks whether an object has any undefined values inside. */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { +function hasUndefined(obj) { + if (obj === undefined) { + return true; + } + if (obj) { + if (Array.isArray(obj)) { + for (let i = 0, len = obj.length; i < len; i++) { + if (hasUndefined(obj[i])) { + return true; + } + } + } + else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) { + if (hasUndefined(obj[objKeys[i]])) { + return true; + } + } + } + } + return false; +} +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" + ? JSON.stringify(args[key], null, 2) + : args[key]; // pretty print + if (typeof value !== "undefined") { + messageParts.push(`${key}: ${value}`); + } + } + return messageParts.join("\n"); +} +class PatchError extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { name, index, operation, tree })); + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: name }); - Object.defineProperty(this, "maxRetries", { + Object.defineProperty(this, "index", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: index }); - Object.defineProperty(this, "queue", { + Object.defineProperty(this, "operation", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: operation }); - Object.defineProperty(this, "onFailedResponseHook", { + Object.defineProperty(this, "tree", { enumerable: true, configurable: true, writable: true, - value: void 0 + value: tree }); - Object.defineProperty(this, "debug", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree, }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.debug = params.debug; - if ( true) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist["default"]({ - concurrency: this.maxConcurrency, - }); - } - else { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); - } - this.onFailedResponseHook = params?.onFailedResponseHook; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - const onFailedResponseHook = this.onFailedResponseHook; - return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; - } - else { - throw new Error(error); - } - }), { - async onFailedAttempt(error) { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.message.startsWith("AbortError")) { - throw error; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (error?.code === "ECONNABORTED") { - throw error; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const response = error?.response; - const status = response?.status; - if (status) { - if (STATUS_NO_RETRY.includes(+status)) { - throw error; - } - else if (STATUS_IGNORE.includes(+status)) { - return; - } - if (onFailedResponseHook) { - await onFailedResponseHook(response); - } - } - }, - // If needed we can change some of the defaults here, - // but they're quite sensible. - retries: this.maxRetries, - randomize: true, - }), { throwOnTimeout: true }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - // Note this doesn't cancel the underlying request, - // when available prefer to use the signal option of the underlying call - if (options.signal) { - return Promise.race([ - this.call(callable, ...args), - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); - } - return this.call(callable, ...args); } - fetch(...args) { - return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content }, - }; - // Check for presence of keys in additional_kwargs - if (message?.additional_kwargs && - Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; - } - return converted; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js - -function assertUuid(str, which) { - if (!wrapper_validate(str)) { - const msg = which !== undefined - ? `Invalid UUID for ${which}: ${str}` - : `Invalid UUID: ${str}`; - throw new Error(msg); - } - return str; } -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js -const warnedMessages = {}; -function warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; - } -} - -// EXTERNAL MODULE: ./node_modules/semver/index.js -var semver = __nccwpck_require__(2088); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js +// @ts-nocheck -function isVersionGreaterOrEqual(current_version, target_version) { - const current = parseVersion(current_version); - const target = parseVersion(target_version); - if (!current || !target) { - throw new Error("Invalid version format."); - } - return current.compare(target) >= 0; -} -function parsePromptIdentifier(identifier) { - if (!identifier || - identifier.split("/").length > 2 || - identifier.startsWith("/") || - identifier.endsWith("/") || - identifier.split(":").length > 2) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - const [ownerNamePart, commitPart] = identifier.split(":"); - const commit = commitPart || "latest"; - if (ownerNamePart.includes("/")) { - const [owner, name] = ownerNamePart.split("/", 2); - if (!owner || !name) { - throw new Error(`Invalid identifier format: ${identifier}`); +const JsonPatchError = PatchError; +const deepClone = helpers_deepClone; +/* We use a Javascript hash to store each + function. Each hash entry (property) uses + the operation identifiers specified in rfc6902. + In this way, we can map each patch operation + to its dedicated function in efficient way. + */ +/* The operations applicable to an object */ +const objOps = { + add: function (obj, key, document) { + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function (obj, key, document) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document, removed }; + }, + replace: function (obj, key, document) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document, removed }; + }, + move: function (obj, key, document) { + /* in case move target overwrites an existing value, + return the removed value, this can be taxing performance-wise, + and is potentially unneeded */ + let removed = getValueByPointer(document, this.path); + if (removed) { + removed = helpers_deepClone(removed); } - return [owner, name, commit]; - } - else { - if (!ownerNamePart) { - throw new Error(`Invalid identifier format: ${identifier}`); + const originalValue = applyOperation(document, { + op: "remove", + path: this.from, + }).removed; + applyOperation(document, { + op: "add", + path: this.path, + value: originalValue, + }); + return { newDocument: document, removed }; + }, + copy: function (obj, key, document) { + const valueToCopy = getValueByPointer(document, this.from); + // enforce copy by value so further operations don't affect source (see issue #177) + applyOperation(document, { + op: "add", + path: this.path, + value: helpers_deepClone(valueToCopy), + }); + return { newDocument: document }; + }, + test: function (obj, key, document) { + return { newDocument: document, test: _areEquals(obj[key], this.value) }; + }, + _get: function (obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + }, +}; +/* The operations applicable to an array. Many are the same as for the object */ +var arrOps = { + add: function (arr, i, document) { + if (isInteger(i)) { + arr.splice(i, 0, this.value); } - return ["-", ownerNamePart, commit]; - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js -function getErrorStackTrace(e) { - if (typeof e !== "object" || e == null) - return undefined; - if (!("stack" in e) || typeof e.stack !== "string") - return undefined; - let stack = e.stack; - const prevLine = `${e}`; - if (stack.startsWith(prevLine)) { - stack = stack.slice(prevLine.length); - } - if (stack.startsWith("\n")) { - stack = stack.slice(1); - } - return stack; -} -function printErrorStackTrace(e) { - const stack = getErrorStackTrace(e); - if (stack == null) - return; - console.error(stack); -} + else { + // array props + arr[i] = this.value; + } + // this may be needed when using '-' in an array + return { newDocument: document, index: i }; + }, + remove: function (arr, i, document) { + var removedList = arr.splice(i, 1); + return { newDocument: document, removed: removedList[0] }; + }, + replace: function (arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { newDocument: document, removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get, +}; /** - * LangSmithConflictError - * - * Represents an error that occurs when there's a conflict during an operation, - * typically corresponding to HTTP 409 status code responses. - * - * This error is thrown when an attempt to create or modify a resource conflicts - * with the current state of the resource on the server. Common scenarios include: - * - Attempting to create a resource that already exists - * - Trying to update a resource that has been modified by another process - * - Violating a uniqueness constraint in the data - * - * @extends Error - * - * @example - * try { - * await createProject("existingProject"); - * } catch (error) { - * if (error instanceof ConflictError) { - * console.log("A conflict occurred:", error.message); - * // Handle the conflict, e.g., by suggesting a different project name - * } else { - * // Handle other types of errors - * } - * } - * - * @property {string} name - Always set to 'ConflictError' for easy identification - * @property {string} message - Detailed error message including server response + * Retrieves a value from a JSON document by a JSON pointer. + * Returns the value. * - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 + * @param document The document to get the value from + * @param pointer an escaped JSON pointer + * @return The retrieved value */ -class LangSmithConflictError extends Error { - constructor(message) { - super(message); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = "LangSmithConflictError"; - this.status = 409; +function getValueByPointer(document, pointer) { + if (pointer == "") { + return document; } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; } /** - * Throws an appropriate error based on the response status and body. + * Apply a single JSON Patch Operation on a JSON document. + * Returns the {newDocument, result} of the operation. + * It modifies the `document` and `operation` objects - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. * - * @param response - The fetch Response object - * @param context - Additional context to include in the error message (e.g., operation being performed) - * @throws {LangSmithConflictError} When the response status is 409 - * @throws {Error} For all other non-ok responses + * @param document The document to patch + * @param operation The operation to apply + * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return `{newDocument, result}` after the operation */ -async function raiseForStatus(response, context, consume) { - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - let errorBody; - if (response.ok) { - if (consume) { - errorBody = await response.text(); +function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) { + if (typeof validateOperation == "function") { + validateOperation(operation, 0, document, operation.path); + } + else { + validator(operation, 0); } - return; - } - errorBody = await response.text(); - const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; - if (response.status === 409) { - throw new LangSmithConflictError(fullMessage); - } - const err = new Error(fullMessage); - err.status = response.status; - throw err; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js -/* eslint-disable */ -// @ts-nocheck -var LIMIT_REPLACE_NODE = "[...]"; -var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; -var arr = []; -var replacerStack = []; -const encoder = new TextEncoder(); -function defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER, - }; -} -function encodeString(str) { - return encoder.encode(str); -} -// Regular stringify -function serialize(obj, errorContext, replacer, spacer, options) { - try { - const str = JSON.stringify(obj, replacer, spacer); - return encodeString(str); } - catch (e) { - // Fall back to more complex stringify if circular reference - if (!e.message?.includes("Converting circular structure to JSON")) { - console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); - return encodeString("[Unserializable]"); + /* ROOT OPERATIONS */ + if (operation.path === "") { + let returnValue = { newDocument: document }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; } - console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); - if (typeof options === "undefined") { - options = defaultOptions(); + else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document; //document we removed + return returnValue; } - decirc(obj, "", 0, [], undefined, 0, options); - let res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer); - } - else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + else if (operation.op === "move" || operation.op === "copy") { + // it's a move or copy to root + returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field + if (operation.op === "move") { + // report removed item + returnValue.removed = document; } + return returnValue; } - catch (_) { - return encodeString("[unable to serialize, circular reference is too complex to analyze]"); - } - finally { - while (arr.length !== 0) { - const part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } - else { - part[0][part[1]] = part[2]; - } + else if (operation.op === "test") { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); } + returnValue.newDocument = document; + return returnValue; } - return encodeString(res); - } -} -function setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - arr.push([parent, k, val, propertyDescriptor]); + else if (operation.op === "remove") { + // a remove on root + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; + } + else if (operation.op === "_get") { + operation.value = document; + return returnValue; } else { - replacerStack.push([val, k, replace]); + /* bad operation */ + if (validateOperation) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + } + else { + return returnValue; + } } - } + } /* END ROOT OPERATIONS */ else { - parent[k] = replace; - arr.push([parent, k, val]); - } -} -function decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } + if (!mutateDocument) { + document = helpers_deepClone(document); } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document; + let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift + let len = keys.length; + let existingPathFragment = undefined; + let key; + let validateFunction; + if (typeof validateOperation == "function") { + validateFunction = validateOperation; } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + else { + validateFunction = validator; } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options); + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) { + key = unescapePathComponent(key); } - } - else { - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - decirc(val[key], key, i, stack, val, depth, options); + if (banPrototypeModifications && + (key == "__proto__" || + (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + } + if (validateOperation) { + if (existingPathFragment === undefined) { + if (obj[key] === undefined) { + existingPathFragment = keys.slice(0, t).join("/"); + } + else if (t == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== undefined) { + validateFunction(operation, 0, document, existingPathFragment); + } + } + } + t++; + if (Array.isArray(obj)) { + if (key === "-") { + key = obj.length; + } + else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); + } // only parse key when it's an integer for `arr.prop` to work + else if (isInteger(key)) { + key = ~~key; + } + } + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + } + const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + else { + if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + return returnValue; + } + } + obj = obj[key]; + // If we have more keys in the path, but the next value isn't a non-null object, + // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. + if (validateOperation && t < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); } } - stack.pop(); } } -// Stable-stringify -function compareFunction(a, b) { - if (a < b) { - return -1; +/** + * Apply a full JSON Patch array on a JSON document. + * Returns the {newDocument, result} of the patch. + * It modifies the `document` object and `patch` - it gets the values by reference. + * If you would like to avoid touching your values, clone them: + * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. + * + * @param document The document to patch + * @param patch The patch to apply + * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. + * @param mutateDocument Whether to mutate the original document or clone it before applying + * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. + * @return An array of `{newDocument, result}` after the patch + */ +function core_applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } } - if (a > b) { - return 1; + if (!mutateDocument) { + document = helpers_deepClone(document); } - return 0; -} -function deterministicStringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") { - options = defaultOptions(); + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; // in case root was replaced } - var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; - var res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer); - } - else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); - } + results.newDocument = document; + return results; +} +/** + * Apply a single JSON Patch Operation on a JSON document. + * Returns the updated document. + * Suitable as a reducer. + * + * @param document The document to patch + * @param operation The operation to apply + * @return The updated document + */ +function applyReducer(document, operation, index) { + const operationResult = applyOperation(document, operation); + if (operationResult.test === false) { + // failed test + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); } - catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + return operationResult.newDocument; +} +/** + * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. + * @param {object} operation - operation object (patch) + * @param {number} index - index of operation in the sequence + * @param {object} [document] - object where the operation is supposed to be applied + * @param {string} [existingPathFragment] - comes along with `document` + */ +function validator(operation, index, document, existingPathFragment) { + if (typeof operation !== "object" || + operation === null || + Array.isArray(operation)) { + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); } - finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } - else { - part[0][part[1]] = part[2]; - } - } + else if (!objOps[operation.op]) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); } - return res; -} -function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; + else if (typeof operation.path !== "string") { + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); + } + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { + // paths that aren't empty string should start with "/" + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); + } + else if ((operation.op === "move" || operation.op === "copy") && + typeof operation.from !== "string") { + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + } + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + operation.value === undefined) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + } + else if ((operation.op === "add" || + operation.op === "replace" || + operation.op === "test") && + hasUndefined(operation.value)) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + } + else if (document) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); } } - try { - if (typeof val.toJSON === "function") { - return; + else if (operation.op === "replace" || + operation.op === "remove" || + operation.op === "_get") { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); } } - catch (_) { - return; - } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: undefined, + }; + var error = core_validate([existingValue], document); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); + } } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; + } +} +/** + * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. + * If error is encountered, returns a JsonPatchError object + * @param sequence + * @param document + * @returns {JsonPatchError|undefined} + */ +function core_validate(sequence, document, externalValidator) { + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options); - } + if (document) { + //clone document and sequence so that we can safely try applying operations + core_applyPatch(helpers_deepClone(document), helpers_deepClone(sequence), externalValidator || true); } else { - // Create a temporary object in the required way - var tmp = {}; - var keys = Object.keys(val).sort(compareFunction); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - deterministicDecirc(val[key], key, i, stack, val, depth, options); - tmp[key] = val[key]; - } - if (typeof parent !== "undefined") { - arr.push([parent, k, val]); - parent[k] = tmp; - } - else { - return tmp; + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) { + externalValidator(sequence[i], i, document, undefined); } } - stack.pop(); } -} -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues(replacer) { - replacer = - typeof replacer !== "undefined" - ? replacer - : function (k, v) { - return v; - }; - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - replacerStack.splice(i, 1); - break; - } - } + catch (e) { + if (e instanceof JsonPatchError) { + return e; } - return replacer.call(this, key, val); - }; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js - - - - - - - - - - - -function mergeRuntimeEnvIntoRunCreate(run) { - const runtimeEnv = getRuntimeEnvironment(); - const envVars = getLangChainEnvVarsMetadata(); - const extra = run.extra ?? {}; - const metadata = extra.metadata; - run.extra = { - ...extra, - runtime: { - ...runtimeEnv, - ...extra?.runtime, - }, - metadata: { - ...envVars, - ...(envVars.revision_id || run.revision_id - ? { revision_id: run.revision_id ?? envVars.revision_id } - : {}), - ...metadata, - }, - }; - return run; -} -const getTracingSamplingRate = (configRate) => { - const samplingRateStr = configRate?.toString() ?? - getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); - if (samplingRateStr === undefined) { - return undefined; - } - const samplingRate = parseFloat(samplingRateStr); - if (samplingRate < 0 || samplingRate > 1) { - throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); - } - return samplingRate; -}; -// utility functions -const isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); -}; -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); - } - return result; -} -function trimQuotes(str) { - if (str === undefined) { - return undefined; - } - return str - .trim() - .replace(/^"(.*)"$/, "$1") - .replace(/^'(.*)'$/, "$1"); -} -const handle429 = async (response) => { - if (response?.status === 429) { - const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000; - if (retryAfter > 0) { - await new Promise((resolve) => setTimeout(resolve, retryAfter)); - // Return directly after calling this check - return true; + else { + throw e; } } - // Fall back to existing status checks - return false; -}; -function _formatFeedbackScore(score) { - if (typeof score === "number") { - // Truncate at 4 decimal places - return Number(score.toFixed(4)); - } - return score; } -class AutoBatchQueue { - constructor() { - Object.defineProperty(this, "items", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "sizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - } - peek() { - return this.items[0]; - } - push(item) { - let itemPromiseResolve; - const itemPromise = new Promise((resolve) => { - // Setting itemPromiseResolve is synchronous with promise creation: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise - itemPromiseResolve = resolve; - }); - const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; - this.items.push({ - action: item.action, - payload: item.item, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - itemPromiseResolve: itemPromiseResolve, - itemPromise, - size, - }); - this.sizeBytes += size; - return itemPromise; - } - pop(upToSizeBytes) { - if (upToSizeBytes < 1) { - throw new Error("Number of bytes to pop off may not be less than 1."); - } - const popped = []; - let poppedSizeBytes = 0; - // Pop items until we reach or exceed the size limit - while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && - this.items.length > 0) { - const item = this.items.shift(); - if (item) { - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } +// based on https://github.com/epoberezkin/fast-deep-equal +// MIT License +// Copyright (c) 2017 Evgeny Poberezkin +// 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. +function _areEquals(a, b) { + if (a === b) + return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) + return false; + for (i = length; i-- !== 0;) + if (!_areEquals(a[i], b[i])) + return false; + return true; } - // If there is an item on the queue we were unable to pop, - // just return it as a single batch. - if (popped.length === 0 && this.items.length > 0) { - const item = this.items.shift(); - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; + if (arrA != arrB) + return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) + return false; + for (i = length; i-- !== 0;) + if (!b.hasOwnProperty(keys[i])) + return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) + return false; } - return [ - popped.map((it) => ({ action: it.action, item: it.payload })), - () => popped.forEach((it) => it.itemPromiseResolve()), - ]; + return true; } + return a !== a && b !== b; } -// 20 MB -const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520; -const SERVER_INFO_REQUEST_TIMEOUT = 2500; -class Client { - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchIngestCaller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "hideInputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "hideOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingSampleRate", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "filteredPostUuids", { - enumerable: true, - configurable: true, - writable: true, - value: new Set() - }); - Object.defineProperty(this, "autoBatchTracing", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "autoBatchQueue", { - enumerable: true, - configurable: true, - writable: true, - value: new AutoBatchQueue() - }); - Object.defineProperty(this, "autoBatchTimeout", { + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js +// @ts-nocheck +// Inlined because of ESM import issues +/*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2013-2021 Joachim Wester + * MIT license + */ + + +var beforeDict = new WeakMap(); +class Mirror { + constructor(obj) { + Object.defineProperty(this, "obj", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "autoBatchAggregationDelayMs", { + Object.defineProperty(this, "observers", { enumerable: true, configurable: true, writable: true, - value: 250 + value: new Map() }); - Object.defineProperty(this, "batchSizeBytesLimit", { + Object.defineProperty(this, "value", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "fetchOptions", { + this.obj = obj; + } +} +class ObserverInfo { + constructor(callback, observer) { + Object.defineProperty(this, "callback", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "settings", { + Object.defineProperty(this, "observer", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "blockOnRootRunFinalization", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" - }); - Object.defineProperty(this, "traceBatchConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: 5 - }); - Object.defineProperty(this, "_serverInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "_getServerInfoPromise", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "manualFlushMode", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "debug", { - enumerable: true, - configurable: true, - writable: true, - value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" - }); - const defaultConfig = Client.getDefaultClientConfig(); - this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - if (this.apiUrl.endsWith("/")) { - this.apiUrl = this.apiUrl.slice(0, -1); - } - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - if (this.webUrl?.endsWith("/")) { - this.webUrl = this.webUrl.slice(0, -1); - } - this.timeout_ms = config.timeout_ms ?? 90_000; - this.caller = new AsyncCaller({ - ...(config.callerOptions ?? {}), - debug: config.debug ?? this.debug, - }); - this.traceBatchConcurrency = - config.traceBatchConcurrency ?? this.traceBatchConcurrency; - if (this.traceBatchConcurrency < 1) { - throw new Error("Trace batch concurrency must be positive."); - } - this.debug = config.debug ?? this.debug; - this.batchIngestCaller = new AsyncCaller({ - maxRetries: 2, - maxConcurrency: this.traceBatchConcurrency, - ...(config.callerOptions ?? {}), - onFailedResponseHook: handle429, - debug: config.debug ?? this.debug, - }); - this.hideInputs = - config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; - this.hideOutputs = - config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; - this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; - this.blockOnRootRunFinalization = - config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; - this.batchSizeBytesLimit = config.batchSizeBytesLimit; - this.fetchOptions = config.fetchOptions || {}; - this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + this.callback = callback; + this.observer = observer; } - static getDefaultClientConfig() { - const apiKey = getLangSmithEnvironmentVariable("API_KEY"); - const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? - "https://api.smith.langchain.com"; - const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; - const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; - return { - apiUrl: apiUrl, - apiKey: apiKey, - webUrl: undefined, - hideInputs: hideInputs, - hideOutputs: hideOutputs, - }; +} +function getMirror(obj) { + return beforeDict.get(obj); +} +function getObserverFromMirror(mirror, callback) { + return mirror.observers.get(callback); +} +function removeObserverFromMirror(mirror, observer) { + mirror.observers.delete(observer.callback); +} +/** + * Detach an observer from an object + */ +function unobserve(root, observer) { + observer.unobserve(); +} +/** + * Observes changes made to an object, which can then be retrieved using generate + */ +function observe(obj, callback) { + var patches = []; + var observer; + var mirror = getMirror(obj); + if (!mirror) { + mirror = new Mirror(obj); + beforeDict.set(obj, mirror); } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; - } - else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost:3000"; - return this.webUrl; - } - else if (this.apiUrl.endsWith("/api/v1")) { - this.webUrl = this.apiUrl.replace("/api/v1", ""); - return this.webUrl; - } - else if (this.apiUrl.includes("/api") && - !this.apiUrl.split(".", 1)[0].endsWith("api")) { - this.webUrl = this.apiUrl.replace("/api", ""); - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("eu")) { - this.webUrl = "https://eu.smith.langchain.com"; - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("beta")) { - this.webUrl = "https://beta.smith.langchain.com"; - return this.webUrl; - } - else { - this.webUrl = "https://smith.langchain.com"; - return this.webUrl; - } + else { + const observerInfo = getObserverFromMirror(mirror, callback); + observer = observerInfo && observerInfo.observer; } - get headers() { - const headers = { - "User-Agent": `langsmith-js/${__version__}`, - }; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; - } - return headers; + if (observer) { + return observer; } - async processInputs(inputs) { - if (this.hideInputs === false) { - return inputs; - } - if (this.hideInputs === true) { - return {}; - } - if (typeof this.hideInputs === "function") { - return this.hideInputs(inputs); + observer = {}; + mirror.value = _deepClone(obj); + if (callback) { + observer.callback = callback; + observer.next = null; + var dirtyCheck = () => { + duplex_generate(observer); + }; + var fastCheck = () => { + clearTimeout(observer.next); + observer.next = setTimeout(dirtyCheck); + }; + if (typeof window !== "undefined") { + //not Node + window.addEventListener("mouseup", fastCheck); + window.addEventListener("keyup", fastCheck); + window.addEventListener("mousedown", fastCheck); + window.addEventListener("keydown", fastCheck); + window.addEventListener("change", fastCheck); } - return inputs; } - async processOutputs(outputs) { - if (this.hideOutputs === false) { - return outputs; - } - if (this.hideOutputs === true) { - return {}; - } - if (typeof this.hideOutputs === "function") { - return this.hideOutputs(outputs); + observer.patches = patches; + observer.object = obj; + observer.unobserve = () => { + duplex_generate(observer); + clearTimeout(observer.next); + removeObserverFromMirror(mirror, observer); + if (typeof window !== "undefined") { + window.removeEventListener("mouseup", fastCheck); + window.removeEventListener("keyup", fastCheck); + window.removeEventListener("mousedown", fastCheck); + window.removeEventListener("keydown", fastCheck); + window.removeEventListener("change", fastCheck); } - return outputs; + }; + mirror.observers.set(callback, new ObserverInfo(callback, observer)); + return observer; +} +/** + * Generate an array of patches from an observer + */ +function duplex_generate(observer, invertible = false) { + var mirror = beforeDict.get(observer.object); + _generate(mirror.value, observer.object, observer.patches, "", invertible); + if (observer.patches.length) { + applyPatch(mirror.value, observer.patches); } - async prepareRunCreateOrUpdateInputs(run) { - const runParams = { ...run }; - if (runParams.inputs !== undefined) { - runParams.inputs = await this.processInputs(runParams.inputs); - } - if (runParams.outputs !== undefined) { - runParams.outputs = await this.processOutputs(runParams.outputs); + var temp = observer.patches; + if (temp.length > 0) { + observer.patches = []; + if (observer.callback) { + observer.callback(temp); } - return runParams; - } - async _getResponse(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - return response; } - async _get(path, queryParams) { - const response = await this._getResponse(path, queryParams); - return response.json(); + return temp; +} +// Dirty check if obj is different from mirror, generate patches and update mirror +function _generate(mirror, obj, patches, path, invertible) { + if (obj === mirror) { + return; } - async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { - let offset = Number(queryParams.get("offset")) || 0; - const limit = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset)); - queryParams.set("limit", String(limit)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = transform - ? transform(await response.json()) - : await response.json(); - if (items.length === 0) { - break; - } - yield items; - if (items.length < limit) { - break; - } - offset += items.length; - } + if (typeof obj.toJSON === "function") { + obj = obj.toJSON(); } - async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { - const bodyParams = body ? { ...body } : {}; - while (true) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { - method: requestMethod, - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: JSON.stringify(bodyParams), - }); - const responseBody = await response.json(); - if (!responseBody) { - break; - } - if (!responseBody[dataKey]) { - break; - } - yield responseBody[dataKey]; - const cursors = responseBody.cursors; - if (!cursors) { - break; + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var changed = false; + var deleted = false; + //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (helpers_hasOwnProperty(obj, key) && + !(obj[key] === undefined && + oldVal !== undefined && + Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && + oldVal != null && + typeof newVal == "object" && + newVal != null && + Array.isArray(oldVal) === Array.isArray(newVal)) { + _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); } - if (!cursors.next) { - break; + else { + if (oldVal !== newVal) { + changed = true; + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(oldVal), + }); + } + patches.push({ + op: "replace", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(newVal), + }); + } } - bodyParams.cursor = cursors.next; - } - } - // Allows mocking for tests - _shouldSample() { - if (this.tracingSampleRate === undefined) { - return true; - } - return Math.random() < this.tracingSampleRate; - } - _filterForSampling(runs, patch = false) { - if (this.tracingSampleRate === undefined) { - return runs; } - if (patch) { - const sampled = []; - for (const run of runs) { - if (!this.filteredPostUuids.has(run.id)) { - sampled.push(run); - } - else { - this.filteredPostUuids.delete(run.id); - } + else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) { + patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(oldVal), + }); } - return sampled; + patches.push({ + op: "remove", + path: path + "/" + escapePathComponent(key), + }); + deleted = true; // property has been deleted } else { - // For new runs, sample at trace level to maintain consistency - const sampled = []; - for (const run of runs) { - const traceId = run.trace_id ?? run.id; - // If we've already made a decision about this trace, follow it - if (this.filteredPostUuids.has(traceId)) { - continue; - } - // For new traces, apply sampling - if (run.id === traceId) { - if (this._shouldSample()) { - sampled.push(run); - } - else { - this.filteredPostUuids.add(traceId); - } - } - else { - // Child runs follow their trace's sampling decision - sampled.push(run); - } + if (invertible) { + patches.push({ op: "test", path, value: mirror }); } - return sampled; + patches.push({ op: "replace", path, value: obj }); + changed = true; } } - async _getBatchSizeLimitBytes() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeBytesLimit ?? - serverInfo.batch_ingest_config?.size_limit_bytes ?? - DEFAULT_BATCH_SIZE_LIMIT_BYTES); - } - async _getMultiPartSupport() { - const serverInfo = await this._ensureServerInfo(); - return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); - } - drainAutoBatchQueue(batchSizeLimit) { - const promises = []; - while (this.autoBatchQueue.items.length > 0) { - const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); - if (!batch.length) { - done(); - break; - } - const batchPromise = this._processBatch(batch, done).catch(console.error); - promises.push(batchPromise); - } - return Promise.all(promises); + if (!deleted && newKeys.length == oldKeys.length) { + return; } - async _processBatch(batch, done) { - if (!batch.length) { - done(); - return; - } - try { - const ingestParams = { - runCreates: batch - .filter((item) => item.action === "create") - .map((item) => item.item), - runUpdates: batch - .filter((item) => item.action === "update") - .map((item) => item.item), - }; - const serverInfo = await this._ensureServerInfo(); - if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { - await this.multipartIngestRuns(ingestParams); - } - else { - await this.batchIngestRuns(ingestParams); - } - } - finally { - done(); + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== undefined) { + patches.push({ + op: "add", + path: path + "/" + escapePathComponent(key), + value: helpers_deepClone(obj[key]), + }); } } - async processRunOperation(item) { - clearTimeout(this.autoBatchTimeout); - this.autoBatchTimeout = undefined; - if (item.action === "create") { - item.item = mergeRuntimeEnvIntoRunCreate(item.item); - } - const itemPromise = this.autoBatchQueue.push(item); - if (this.manualFlushMode) { - // Rely on manual flushing in serverless environments - return itemPromise; +} +/** + * Create an array of patches from the differences in two objects + */ +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js + + + +/** + * Default export for backwards compat + */ + + +/* harmony default export */ const fast_json_patch = ({ + ...src_core_namespaceObject, + // ...duplex, + JsonPatchError: PatchError, + deepClone: helpers_deepClone, + escapePathComponent: escapePathComponent, + unescapePathComponent: unescapePathComponent, +}); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/constants.js +// OpenTelemetry GenAI semantic convention attribute names +const GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; +const GEN_AI_SYSTEM = "gen_ai.system"; +const GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; +const GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; +const GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; +const GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; +const GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; +const GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; +const GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; +const GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; +const GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; +const GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; +const GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; +const GENAI_PROMPT = "gen_ai.prompt"; +const GENAI_COMPLETION = "gen_ai.completion"; +const GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; +const GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; +const GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; +const GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; +const GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; +const GEN_AI_RESPONSE_ID = "gen_ai.response.id"; +const GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; +const GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; +const GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; +const GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; +// LangSmith custom attributes +const LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; +const LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; +const LANGSMITH_RUN_TYPE = "langsmith.span.kind"; +const LANGSMITH_NAME = "langsmith.trace.name"; +const LANGSMITH_METADATA = "langsmith.metadata"; +const LANGSMITH_TAGS = "langsmith.span.tags"; +const LANGSMITH_RUNTIME = "langsmith.span.runtime"; +const LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; +const LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; +const LANGSMITH_RUN_ID = "langsmith.span.id"; +const LANGSMITH_TRACE_ID = "langsmith.trace.id"; +const LANGSMITH_DOTTED_ORDER = "langsmith.span.dotted_order"; +const LANGSMITH_PARENT_RUN_ID = "langsmith.span.parent_id"; +const LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; +const LANGSMITH_REFERENCE_EXAMPLE_ID = "langsmith.reference_example_id"; +const LANGSMITH_TRACEABLE = "langsmith.traceable"; +const LANGSMITH_IS_ROOT = "langsmith.is_root"; +const LANGSMITH_TRACEABLE_PARENT_OTEL_SPAN_ID = "langsmith.traceable_parent_otel_span_id"; +// GenAI event names +const GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"; +const GEN_AI_USER_MESSAGE = "gen_ai.user.message"; +const GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"; +const GEN_AI_CHOICE = "gen_ai.choice"; +const AI_SDK_LLM_OPERATIONS = (/* unused pure expression or super */ null && ([ + "ai.generateText.doGenerate", + "ai.streamText.doStream", + "ai.generateObject.doGenerate", + "ai.streamObject.doStream", +])); +const AI_SDK_TOOL_OPERATIONS = (/* unused pure expression or super */ null && (["ai.toolCall"])); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js + +// Wrap the default fetch call due to issues with illegal invocations +// in some environments: +// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err +// @ts-expect-error Broad typing to support a range of fetch implementations +const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); +const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); +/** + * Overrides the fetch implementation used for LangSmith calls. + * You should use this if you need to use an implementation of fetch + * other than the default global (e.g. for dealing with proxies). + * @param fetch The new fetch functino to use. + */ +const overrideFetchImplementation = (fetch) => { + globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; +}; +const _globalFetchImplementationIsNodeFetch = () => { + const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; + if (!fetchImpl) + return false; + // Check if the implementation has node-fetch specific properties + return (typeof fetchImpl === "function" && + "Headers" in fetchImpl && + "Request" in fetchImpl && + "Response" in fetchImpl); +}; +/** + * @internal + */ +const _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`→ ${options?.method || "GET"} ${url}`); } - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { - void this.drainAutoBatchQueue(sizeLimitBytes); + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? + DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + console.log(`← ${res.status} ${res.statusText} ${res.url}`); } - if (this.autoBatchQueue.items.length > 0) { - this.autoBatchTimeout = setTimeout(() => { - this.autoBatchTimeout = undefined; - void this.drainAutoBatchQueue(sizeLimitBytes); - }, this.autoBatchAggregationDelayMs); - } - return itemPromise; + return res; + }; +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/project.js + +const getDefaultProjectName = () => { + return (getLangSmithEnvironmentVariable("PROJECT") ?? + getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default"); +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js + + + + +// Update using yarn bump-version +const __version__ = "0.3.55"; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js +// Inlined from https://github.com/flexdinesh/browser-or-node + +let globalEnv; +const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !isDeno(); +const getEnv = () => { + if (globalEnv) { + return globalEnv; } - async _getServerInfo() { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/info`, { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), - ...this.fetchOptions, - }); - await raiseForStatus(response, "get server info"); - const json = await response.json(); - if (this.debug) { - console.log("\n=== LangSmith Server Configuration ===\n" + - JSON.stringify(json, null, 2) + - "\n"); + if (isBrowser()) { + globalEnv = "browser"; + } + else if (isNode()) { + globalEnv = "node"; + } + else if (isWebWorker()) { + globalEnv = "webworker"; + } + else if (isJsDom()) { + globalEnv = "jsdom"; + } + else if (isDeno()) { + globalEnv = "deno"; + } + else { + globalEnv = "other"; + } + return globalEnv; +}; +let runtimeEnvironment; +function getRuntimeEnvironment() { + if (runtimeEnvironment === undefined) { + const env = getEnv(); + const releaseEnv = getShas(); + runtimeEnvironment = { + library: "langsmith", + runtime: env, + sdk: "langsmith-js", + sdk_version: __version__, + ...releaseEnv, + }; + } + return runtimeEnvironment; +} +/** + * Retrieves the LangChain-specific environment variables from the current runtime environment. + * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security. + * + * @returns {Record} + * - A record of LangChain-specific environment variables. + */ +function getLangChainEnvVars() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + for (const [key, value] of Object.entries(allEnvVars)) { + if (key.startsWith("LANGCHAIN_") && typeof value === "string") { + envVars[key] = value; } - return json; } - async _ensureServerInfo() { - if (this._getServerInfoPromise === undefined) { - this._getServerInfoPromise = (async () => { - if (this._serverInfo === undefined) { - try { - this._serverInfo = await this._getServerInfo(); - } - catch (e) { - console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); - } - } - return this._serverInfo ?? {}; - })(); + for (const key in envVars) { + if ((key.toLowerCase().includes("key") || + key.toLowerCase().includes("secret") || + key.toLowerCase().includes("token")) && + typeof envVars[key] === "string") { + const value = envVars[key]; + envVars[key] = + value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); } - return this._getServerInfoPromise.then((serverInfo) => { - if (this._serverInfo === undefined) { - this._getServerInfoPromise = undefined; + } + return envVars; +} +/** + * Retrieves the LangChain-specific metadata from the current runtime environment. + * + * @returns {Record} + * - A record of LangChain-specific metadata environment variables. + */ +function getLangChainEnvVarsMetadata() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION", + ]; + for (const [key, value] of Object.entries(allEnvVars)) { + if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && + typeof value === "string" && + !excluded.includes(key) && + !key.toLowerCase().includes("key") && + !key.toLowerCase().includes("secret") && + !key.toLowerCase().includes("token")) { + if (key === "LANGCHAIN_REVISION_ID") { + envVars["revision_id"] = value; } - return serverInfo; - }); + else { + envVars[key] = value; + } + } } - async _getSettings() { - if (!this.settings) { - this.settings = this._get("/settings"); + return envVars; +} +/** + * Retrieves the environment variables from the current runtime environment. + * + * This function is designed to operate in a variety of JS environments, + * including Node.js, Deno, browsers, etc. + * + * @returns {Record | undefined} + * - A record of environment variables if available. + * - `undefined` if the environment does not support or allows access to environment variables. + */ +function getEnvironmentVariables() { + try { + // Check for Node.js environment + // eslint-disable-next-line no-process-env + if (typeof process !== "undefined" && process.env) { + // eslint-disable-next-line no-process-env + return Object.entries(process.env).reduce((acc, [key, value]) => { + acc[key] = String(value); + return acc; + }, {}); } - return await this.settings; + // For browsers and other environments, we may not have direct access to env variables + // Return undefined or any other fallback as required. + return undefined; } - /** - * Flushes current queued traces. - */ - async flush() { - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - await this.drainAutoBatchQueue(sizeLimitBytes); + catch (e) { + // Catch any errors that might occur while trying to access environment variables + return undefined; } - async createRun(run) { - if (!this._filterForSampling([run]).length) { - return; +} +function getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/hwchase17/langchainjs/issues/1412 + try { + return typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.[name] + : undefined; + } + catch (e) { + return undefined; + } +} +function getLangSmithEnvironmentVariable(name) { + return (getEnvironmentVariable(`LANGSMITH_${name}`) || + getEnvironmentVariable(`LANGCHAIN_${name}`)); +} +function setEnvironmentVariable(name, value) { + if (typeof process !== "undefined") { + // eslint-disable-next-line no-process-env + process.env[name] = value; + } +} +let cachedCommitSHAs; +/** + * Get the Git commit SHA from common environment variables + * used by different CI/CD platforms. + * @returns {string | undefined} The Git commit SHA or undefined if not found. + */ +function getShas() { + if (cachedCommitSHAs !== undefined) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT", + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = getEnvironmentVariable(env); + if (envVar !== undefined) { + shas[env] = envVar; } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const session_name = run.project_name; - delete run.project_name; - const runCreate = await this.prepareRunCreateOrUpdateInputs({ - session_name, - ...run, - start_time: run.start_time ?? Date.now(), + } + cachedCommitSHAs = shas; + return shas; +} +function getOtelEnabled() { + return (getEnvironmentVariable("OTEL_ENABLED") === "true" || + getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/otel.js +// Should not import any OTEL packages to avoid pulling in optional deps. + +class MockTracer { + constructor() { + Object.defineProperty(this, "hasWarned", { + enumerable: true, + configurable: true, + writable: true, + value: false }); - if (this.autoBatchTracing && - runCreate.trace_id !== undefined && - runCreate.dotted_order !== undefined) { - void this.processRunOperation({ - action: "create", - item: runCreate, - }).catch(console.error); - return; + } + startActiveSpan(_name, ...args) { + if (!this.hasWarned && getOtelEnabled()) { + console.warn("You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. " + + 'Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); + this.hasWarned = true; } - const mergedRunCreateParam = mergeRuntimeEnvIntoRunCreate(runCreate); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs`, { - method: "POST", - headers, - body: serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + // Handle different overloads: + // startActiveSpan(name, fn) + // startActiveSpan(name, options, fn) + // startActiveSpan(name, options, context, fn) + let fn; + if (args.length === 1 && typeof args[0] === "function") { + fn = args[0]; + } + else if (args.length === 2 && typeof args[1] === "function") { + fn = args[1]; + } + else if (args.length === 3 && typeof args[2] === "function") { + fn = args[2]; + } + if (typeof fn === "function") { + return fn(); + } + return undefined; + } +} +class MockOTELTrace { + constructor() { + Object.defineProperty(this, "mockTracer", { + enumerable: true, + configurable: true, + writable: true, + value: new MockTracer() }); - await raiseForStatus(response, "create run", true); } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async batchIngestRuns({ runCreates, runUpdates, }) { - if (runCreates === undefined && runUpdates === undefined) { - return; + getTracer(_name, _version) { + return this.mockTracer; + } + getActiveSpan() { + return undefined; + } + setSpan(context, _span) { + return context; + } + getSpan(_context) { + return undefined; + } + setSpanContext(context, _spanContext) { + return context; + } + getTracerProvider() { + return undefined; + } + setGlobalTracerProvider(_tracerProvider) { + return false; + } +} +class MockOTELContext { + active() { + return {}; + } + with(_context, fn) { + return fn(); + } +} +const OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); +const OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); +const OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); +const mockOTELTrace = new MockOTELTrace(); +const mockOTELContext = new MockOTELContext(); +class OTELProvider { + getTraceInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; + } + getContextInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; + } + initializeGlobalInstances(otel) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[OTEL_TRACE_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_TRACE_KEY] = otel.trace; } - let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); - let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[OTEL_CONTEXT_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_CONTEXT_KEY] = otel.context; + } + } + setDefaultOTLPTracerComponents(components) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; + } + getDefaultOTLPTracerComponents() { + return (globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? + undefined); + } +} +const OTELProviderSingleton = new OTELProvider(); +/** + * Get the current OTEL trace instance. + * Returns a mock implementation if OTEL is not available. + */ +function getOTELTrace() { + return OTELProviderSingleton.getTraceInstance(); +} +/** + * Get the current OTEL context instance. + * Returns a mock implementation if OTEL is not available. + */ +function getOTELContext() { + return OTELProviderSingleton.getContextInstance(); +} +/** + * Initialize the global OTEL instances. + * Should be called once when OTEL packages are available. + */ +function setOTELInstances(otel) { + OTELProviderSingleton.initializeGlobalInstances(otel); +} +/** + * Set a getter function for the default OTLP tracer provider. + * This allows lazy initialization of the tracer provider. + */ +function setDefaultOTLPTracerComponents(components) { + OTELProviderSingleton.setDefaultOTLPTracerComponents(components); +} +/** + * Get the default OTLP tracer provider instance. + * Returns undefined if not set. + */ +function getDefaultOTLPTracerComponents() { + return OTELProviderSingleton.getDefaultOTLPTracerComponents(); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/translator.js + + +const WELL_KNOWN_OPERATION_NAMES = { + llm: "chat", + tool: "execute_tool", + retriever: "embeddings", + embedding: "embeddings", + prompt: "chat", +}; +function getOperationName(runType) { + return WELL_KNOWN_OPERATION_NAMES[runType] || runType; +} +class LangSmithToOTELTranslator { + constructor() { + Object.defineProperty(this, "spans", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + } + exportBatch(operations, otelContextMap) { + for (const op of operations) { + try { + if (!op.run) { + continue; } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; + if (op.operation === "post") { + const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); + if (span && !op.run.end_time) { + this.spans.set(op.id, span); + } } else { - standaloneUpdates.push(updateParam); + this.updateSpanForRun(op, op.run); } } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; + catch (e) { + console.error(`Error processing operation ${op.id}:`, e); + } } - const rawBatch = { - post: preparedCreateParams, - patch: preparedUpdateParams, - }; - if (!rawBatch.post.length && !rawBatch.patch.length) { + } + createSpanForRun(op, runInfo, otelContext) { + const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); + if (!activeSpan) { return; } - const batchChunks = { - post: [], - patch: [], - }; - for (const k of ["post", "patch"]) { - const key = k; - const batchItems = rawBatch[key].reverse(); - let batchItem = batchItems.pop(); - while (batchItem !== undefined) { - // Type is wrong but this is a deprecated code path anyway - batchChunks[key].push(batchItem); - batchItem = batchItems.pop(); - } + try { + return this.finishSpanSetup(activeSpan, runInfo, op); } - if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { - const runIds = batchChunks.post - .map((item) => item.id) - .concat(batchChunks.patch.map((item) => item.id)) - .join(","); - await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`)); + catch (e) { + console.error(`Failed to create span for run ${op.id}:`, e); + return undefined; } } - async _postBatchIngestRuns(body) { - const headers = { - ...this.headers, - "Content-Type": "application/json", - Accept: "application/json", - }; - const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/batch`, { - method: "POST", - headers, - body: body, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "batch create run", true); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async multipartIngestRuns({ runCreates, runUpdates, }) { - if (runCreates === undefined && runUpdates === undefined) { - return; + finishSpanSetup(span, runInfo, op) { + // Set all attributes + this.setSpanAttributes(span, runInfo, op); + // Set status based on error + if (runInfo.error) { + span.setStatus({ code: 2 }); // ERROR status + span.recordException(new Error(runInfo.error)); } - // transform and convert to dicts - const allAttachments = {}; - let preparedCreateParams = []; - for (const create of runCreates ?? []) { - const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); - if (preparedCreate.id !== undefined && - preparedCreate.attachments !== undefined) { - allAttachments[preparedCreate.id] = preparedCreate.attachments; - } - delete preparedCreate.attachments; - preparedCreateParams.push(preparedCreate); + else { + span.setStatus({ code: 1 }); // OK status } - let preparedUpdateParams = []; - for (const update of runUpdates ?? []) { - preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); + // End the span if end_time is present + if (runInfo.end_time) { + span.end(new Date(runInfo.end_time)); } - // require trace_id and dotted_order - const invalidRunCreate = preparedCreateParams.find((runCreate) => { - return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); - }); - if (invalidRunCreate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + return span; + } + updateSpanForRun(op, runInfo) { + try { + const span = this.spans.get(op.id); + if (!span) { + console.debug(`No span found for run ${op.id} during update`); + return; + } + // Update attributes + this.setSpanAttributes(span, runInfo, op); + // Update status based on error + if (runInfo.error) { + span.setStatus({ code: 2 }); // ERROR status + span.recordException(new Error(runInfo.error)); + } + else { + span.setStatus({ code: 1 }); // OK status + } + // End the span if end_time is present + const endTime = runInfo.end_time; + if (endTime) { + span.end(new Date(endTime)); + this.spans.delete(op.id); + } } - const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { - return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); - }); - if (invalidRunUpdate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + catch (e) { + console.error(`Failed to update span for run ${op.id}:`, e); } - // combine post and patch dicts where possible - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; + } + extractModelName(runInfo) { + // Try to get model name from metadata + if (runInfo.extra?.metadata) { + const metadata = runInfo.extra.metadata; + // First check for ls_model_name in metadata + if (metadata.ls_model_name) { + return metadata.ls_model_name; + } + // Then check invocation_params for model info + if (metadata.invocation_params) { + const invocationParams = metadata.invocation_params; + if (invocationParams.model) { + return invocationParams.model; } - else { - standaloneUpdates.push(updateParam); + else if (invocationParams.model_name) { + return invocationParams.model_name; } } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; } - if (preparedCreateParams.length === 0 && - preparedUpdateParams.length === 0) { - return; + return; + } + setSpanAttributes(span, runInfo, op) { + if ("run_type" in runInfo && runInfo.run_type) { + span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); + // Set GenAI attributes according to OTEL semantic conventions + const operationName = getOperationName(runInfo.run_type || "chain"); + span.setAttribute(GEN_AI_OPERATION_NAME, operationName); } - // send the runs in multipart requests - const accumulatedContext = []; - const accumulatedParts = []; - for (const [method, payloads] of [ - ["post", preparedCreateParams], - ["patch", preparedUpdateParams], - ]) { - for (const originalPayload of payloads) { - // collect fields to be sent as separate parts - const { inputs, outputs, events, attachments, ...payload } = originalPayload; - const fields = { inputs, outputs, events }; - // encode the main run payload - const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); - accumulatedParts.push({ - name: `${method}.${payload.id}`, - payload: new Blob([stringifiedPayload], { - type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip - }), - }); - // encode the fields we collected - for (const [key, value] of Object.entries(fields)) { - if (value === undefined) { - continue; - } - const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); - accumulatedParts.push({ - name: `${method}.${payload.id}.${key}`, - payload: new Blob([stringifiedValue], { - type: `application/json; length=${stringifiedValue.length}`, - }), - }); - } - // encode the attachments - if (payload.id !== undefined) { - const attachments = allAttachments[payload.id]; - if (attachments) { - delete allAttachments[payload.id]; - for (const [name, attachment] of Object.entries(attachments)) { - let contentType; - let content; - if (Array.isArray(attachment)) { - [contentType, content] = attachment; - } - else { - contentType = attachment.mimeType; - content = attachment.data; - } - // Validate that the attachment name doesn't contain a '.' - if (name.includes(".")) { - console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + - `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); - continue; - } - accumulatedParts.push({ - name: `attachment.${payload.id}.${name}`, - payload: new Blob([content], { - type: `${contentType}; length=${content.byteLength}`, - }), - }); - } - } - } - // compute context - accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); - } + if ("name" in runInfo && runInfo.name) { + span.setAttribute(LANGSMITH_NAME, runInfo.name); } - await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; ")); - } - async _createNodeFetchBody(parts, boundary) { - // Create multipart form data manually using Blobs - const chunks = []; - for (const part of parts) { - // Add field boundary - chunks.push(new Blob([`--${boundary}\r\n`])); - chunks.push(new Blob([ - `Content-Disposition: form-data; name="${part.name}"\r\n`, - `Content-Type: ${part.payload.type}\r\n\r\n`, - ])); - chunks.push(part.payload); - chunks.push(new Blob(["\r\n"])); + if ("session_id" in runInfo && runInfo.session_id) { + span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); } - // Add final boundary - chunks.push(new Blob([`--${boundary}--\r\n`])); - // Combine all chunks into a single Blob - const body = new Blob(chunks); - // Convert Blob to ArrayBuffer for compatibility - const arrayBuffer = await body.arrayBuffer(); - return arrayBuffer; - } - async _createMultipartStream(parts, boundary) { - const encoder = new TextEncoder(); - // Create a ReadableStream for streaming the multipart data - // Only do special handling if we're using node-fetch - const stream = new ReadableStream({ - async start(controller) { - // Helper function to write a chunk to the stream - const writeChunk = async (chunk) => { - if (typeof chunk === "string") { - controller.enqueue(encoder.encode(chunk)); - } - else { - controller.enqueue(chunk); - } - }; - // Write each part to the stream - for (const part of parts) { - // Write boundary and headers - await writeChunk(`--${boundary}\r\n`); - await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); - await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); - // Write the payload - const payloadStream = part.payload.stream(); - const reader = payloadStream.getReader(); - try { - let result; - while (!(result = await reader.read()).done) { - controller.enqueue(result.value); - } - } - finally { - reader.releaseLock(); - } - await writeChunk("\r\n"); - } - // Write final boundary - await writeChunk(`--${boundary}--\r\n`); - controller.close(); - }, - }); - return stream; - } - async _sendMultipartRequest(parts, context) { - try { - // Create multipart form data boundary - const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); - const body = await (_globalFetchImplementationIsNodeFetch() - ? this._createNodeFetchBody(parts, boundary) - : this._createMultipartStream(parts, boundary)); - const res = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/multipart`, { - method: "POST", - headers: { - ...this.headers, - "Content-Type": `multipart/form-data; boundary=${boundary}`, - }, - body, - duplex: "half", - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "ingest multipart runs", true); - // eslint-disable-next-line @typescript-eslint/no-explicit-any + if ("session_name" in runInfo && runInfo.session_name) { + span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); } - catch (e) { - console.warn(`${e.message.trim()}\n\nContext: ${context}`); + // Set gen_ai.system + this.setGenAiSystem(span, runInfo); + // Set model name if available + const modelName = this.extractModelName(runInfo); + if (modelName) { + span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); } - } - async updateRun(runId, run) { - assertUuid(runId); - if (run.inputs) { - run.inputs = await this.processInputs(run.inputs); + // Set token usage information + if ("prompt_tokens" in runInfo && + typeof runInfo.prompt_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); } - if (run.outputs) { - run.outputs = await this.processOutputs(run.outputs); + if ("completion_tokens" in runInfo && + typeof runInfo.completion_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); } - // TODO: Untangle types - const data = { ...run, id: runId }; - if (!this._filterForSampling([data], true).length) { - return; + if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); } - if (this.autoBatchTracing && - data.trace_id !== undefined && - data.dotted_order !== undefined) { - if (run.end_time !== undefined && - data.parent_run_id === undefined && - this.blockOnRootRunFinalization && - !this.manualFlushMode) { - // Trigger batches as soon as a root trace ends and wait to ensure trace finishes - // in serverless environments. - await this.processRunOperation({ action: "update", item: data }).catch(console.error); - return; - } - else { - void this.processRunOperation({ action: "update", item: data }).catch(console.error); + // Set other parameters from invocation_params + this.setInvocationParameters(span, runInfo); + // Set metadata and tags if available + const metadata = runInfo.extra?.metadata || {}; + for (const [key, value] of Object.entries(metadata)) { + if (value !== null && value !== undefined) { + span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); } - return; } - const headers = { ...this.headers, "Content-Type": "application/json" }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - body: serialize(run, `Serializing payload to update run with id: ${runId}`), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update run", true); - } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - assertUuid(runId); - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns) { - run = await this._loadChildRuns(run); + const tags = runInfo.tags; + if (tags && Array.isArray(tags)) { + span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); } - return run; + else if (tags) { + span.setAttribute(LANGSMITH_TAGS, String(tags)); + } + // Support additional serialized attributes, if present + if ("serialized" in runInfo && typeof runInfo.serialized === "object") { + const serialized = runInfo.serialized; + if (serialized.name) { + span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); + } + if (serialized.signature) { + span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); + } + if (serialized.doc) { + span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); + } + } + // Set inputs/outputs if available + this.setIOAttributes(span, op); } - async getRunUrl({ runId, run, projectOpts, }) { - if (run !== undefined) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; + setGenAiSystem(span, runInfo) { + // Default to "langchain" if we can't determine the system + let system = "langchain"; + // Extract model name to determine the system + const modelName = this.extractModelName(runInfo); + if (modelName) { + const modelLower = modelName.toLowerCase(); + if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { + system = "anthropic"; } - else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + else if (modelLower.includes("bedrock")) { + system = "aws.bedrock"; } - else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; + else if (modelLower.includes("azure") && + modelLower.includes("openai")) { + system = "az.ai.openai"; } - else { - const project = await this.readProject({ - projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", - }); - sessionId = project.id; + else if (modelLower.includes("azure") && + modelLower.includes("inference")) { + system = "az.ai.inference"; } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; - } - else if (runId !== undefined) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); + else if (modelLower.includes("cohere")) { + system = "cohere"; } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; - } - else { - throw new Error("Must provide either runId or run"); - } - } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ - isRoot: false, - projectId: run.session_id, - traceId: run.trace_id, - })); - const treemap = {}; - const runs = {}; - // TODO: make dotted order required when the migration finishes - childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || - childRun.parent_run_id === undefined) { - throw new Error(`Child run ${childRun.id} has no parent`); + else if (modelLower.includes("deepseek")) { + system = "deepseek"; } - if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && - childRun.id !== run.id) { - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; + else if (modelLower.includes("gemini")) { + system = "gemini"; } - } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; + else if (modelLower.includes("groq")) { + system = "groq"; + } + else if (modelLower.includes("watson") || modelLower.includes("ibm")) { + system = "ibm.watsonx.ai"; + } + else if (modelLower.includes("mistral")) { + system = "mistral_ai"; + } + else if (modelLower.includes("gpt") || modelLower.includes("openai")) { + system = "openai"; + } + else if (modelLower.includes("perplexity") || + modelLower.includes("sonar")) { + system = "perplexity"; + } + else if (modelLower.includes("vertex")) { + system = "vertex_ai"; + } + else if (modelLower.includes("xai") || modelLower.includes("grok")) { + system = "xai"; } } - return run; + span.setAttribute(GEN_AI_SYSTEM, system); } - /** - * List runs from the LangSmith server. - * @param projectId - The ID of the project to filter by. - * @param projectName - The name of the project to filter by. - * @param parentRunId - The ID of the parent run to filter by. - * @param traceId - The ID of the trace to filter by. - * @param referenceExampleId - The ID of the reference example to filter by. - * @param startTime - The start time to filter by. - * @param isRoot - Indicates whether to only return root runs. - * @param runType - The run type to filter by. - * @param error - Indicates whether to filter by error runs. - * @param id - The ID of the run to filter by. - * @param query - The query string to filter by. - * @param filter - The filter string to apply to the run spans. - * @param traceFilter - The filter string to apply on the root run of the trace. - * @param treeFilter - The filter string to apply on other runs in the trace. - * @param limit - The maximum number of runs to retrieve. - * @returns {AsyncIterable} - The runs. - * - * @example - * // List all runs in a project - * const projectRuns = client.listRuns({ projectName: "" }); - * - * @example - * // List LLM and Chat runs in the last 24 hours - * const todaysLLMRuns = client.listRuns({ - * projectName: "", - * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), - * run_type: "llm", - * }); - * - * @example - * // List traces in a project - * const rootRuns = client.listRuns({ - * projectName: "", - * execution_order: 1, - * }); - * - * @example - * // List runs without errors - * const correctRuns = client.listRuns({ - * projectName: "", - * error: false, - * }); - * - * @example - * // List runs by run ID - * const runIds = [ - * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", - * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", - * ]; - * const selectedRuns = client.listRuns({ run_ids: runIds }); - * - * @example - * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 - * const chainRuns = client.listRuns({ - * projectName: "", - * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', - * }); - * - * @example - * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 - * const goodExtractorRuns = client.listRuns({ - * projectName: "", - * filter: 'eq(name, "extractor")', - * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', - * }); - * - * @example - * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 - * const complexRuns = client.listRuns({ - * projectName: "", - * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', - * }); - * - * @example - * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds - * const taggedRuns = client.listRuns({ - * projectName: "", - * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', - * }); - */ - async *listRuns(props) { - const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; - let projectIds = []; - if (projectId) { - projectIds = Array.isArray(projectId) ? projectId : [projectId]; + setInvocationParameters(span, runInfo) { + if (!runInfo.extra?.metadata?.invocation_params) { + return; } - if (projectName) { - const projectNames = Array.isArray(projectName) - ? projectName - : [projectName]; - const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); - projectIds.push(...projectIds_); + const invocationParams = runInfo.extra.metadata.invocation_params; + // Set relevant invocation parameters + if (invocationParams.max_tokens !== undefined) { + span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); } - const default_select = [ - "app_path", - "completion_cost", - "completion_tokens", - "dotted_order", - "end_time", - "error", - "events", - "extra", - "feedback_stats", - "first_token_time", - "id", - "inputs", - "name", - "outputs", - "parent_run_id", - "parent_run_ids", - "prompt_cost", - "prompt_tokens", - "reference_example_id", - "run_type", - "session_id", - "start_time", - "status", - "tags", - "total_cost", - "total_tokens", - "trace_id", - ]; - const body = { - session: projectIds.length ? projectIds : null, - run_type: runType, - reference_example: referenceExampleId, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - execution_order: executionOrder, - parent_run: parentRunId, - start_time: startTime ? startTime.toISOString() : null, - error, - id, - limit, - trace: traceId, - select: select ? select : default_select, - is_root: isRoot, - order, - }; - let runsYielded = 0; - for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { - if (limit) { - if (runsYielded >= limit) { - break; + if (invocationParams.temperature !== undefined) { + span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); + } + if (invocationParams.top_p !== undefined) { + span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); + } + if (invocationParams.frequency_penalty !== undefined) { + span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); + } + if (invocationParams.presence_penalty !== undefined) { + span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); + } + } + setIOAttributes(span, op) { + if (op.run.inputs) { + try { + const inputs = op.run.inputs; + if (typeof inputs === "object" && inputs !== null) { + if (inputs.model && Array.isArray(inputs.messages)) { + span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); + } + // Set additional request attributes if available + if (inputs.stream !== undefined) { + span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); + } + if (inputs.extra_headers) { + span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); + } + if (inputs.extra_query) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); + } + if (inputs.extra_body) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); + } } - if (runs.length + runsYielded > limit) { - const newRuns = runs.slice(0, limit - runsYielded); - yield* newRuns; - break; + span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); + } + catch (e) { + console.debug(`Failed to process inputs for run ${op.id}`, e); + } + } + if (op.run.outputs) { + try { + const outputs = op.run.outputs; + // Extract token usage from outputs (for LLM runs) + const tokenUsage = this.getUnifiedRunTokens(outputs); + if (tokenUsage) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); + } + if (outputs && typeof outputs === "object") { + if (outputs.model) { + span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); + } + // Extract additional response attributes + if (outputs.id) { + span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); + } + if (outputs.choices && Array.isArray(outputs.choices)) { + const finishReasons = outputs.choices + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map((choice) => choice.finish_reason) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .filter((reason) => reason) + .map(String); + if (finishReasons.length > 0) { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); + } + } + if (outputs.service_tier) { + span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); + } + if (outputs.system_fingerprint) { + span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); + } + if (outputs.usage_metadata && + typeof outputs.usage_metadata === "object") { + const usageMetadata = outputs.usage_metadata; + if (usageMetadata.input_token_details) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); + } + if (usageMetadata.output_token_details) { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); + } + } } - runsYielded += runs.length; - yield* runs; + span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); } - else { - yield* runs; + catch (e) { + console.debug(`Failed to process outputs for run ${op.id}`, e); } } } - async *listGroupRuns(props) { - const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; - const sessionId = projectId || (await this.readProject({ projectName })).id; - const baseBody = { - session_id: sessionId, - group_by: groupBy, - filter, - start_time: startTime ? startTime.toISOString() : null, - end_time: endTime ? endTime.toISOString() : null, - limit: Number(limit) || 100, - }; - let currentOffset = Number(offset) || 0; - const path = "/runs/group"; - const url = `${this.apiUrl}${path}`; - while (true) { - const currentBody = { - ...baseBody, - offset: currentOffset, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); - const response = await this.caller.call(_getFetchImplementation(), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(filteredPayload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to fetch ${path}`); - const items = await response.json(); - const { groups, total } = items; - if (groups.length === 0) { - break; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getUnifiedRunTokens(outputs) { + if (!outputs) { + return null; + } + // Search in non-generations lists + let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + // Find if direct kwarg in outputs + const keys = Object.keys(outputs); + for (const key of keys) { + const haystack = outputs[key]; + if (!haystack || typeof haystack !== "object") { + continue; } - for (const thread of groups) { - yield thread; + tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); + if (tokenUsage) { + return tokenUsage; } - currentOffset += groups.length; - if (currentOffset >= total) { - break; + if (haystack.lc === 1 && + haystack.kwargs && + typeof haystack.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + // Find in generations + const generations = outputs.generations || []; + if (!Array.isArray(generations)) { + return null; + } + const flatGenerations = Array.isArray(generations[0]) + ? generations.flat() + : generations; + for (const generation of flatGenerations) { + if (typeof generation === "object" && + generation.message && + typeof generation.message === "object" && + generation.message.kwargs && + typeof generation.message.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } } } + return null; } - async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { - let projectIds_ = projectIds || []; - if (projectNames) { - projectIds_ = [ - ...(projectIds || []), - ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), - ]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + extractUnifiedRunTokens(outputs) { + if (!outputs || typeof outputs !== "object") { + return null; } - const payload = { - id, - trace, - parent_run: parentRun, - run_type: runType, - session: projectIds_, - reference_example: referenceExampleIds, - start_time: startTime, - end_time: endTime, - error, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - is_root: isRoot, - data_source_type: dataSourceType, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { - method: "POST", - headers: this.headers, - body: JSON.stringify(filteredPayload), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const result = await response.json(); - return result; + if (typeof outputs.input_tokens !== "number" || + typeof outputs.output_tokens !== "number") { + return null; + } + return [outputs.input_tokens, outputs.output_tokens]; } - async shareRun(runId, { shareId } = {}) { - const data = { - run_id: runId, - share_token: shareId || v4(), - }; - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, +} + +// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js +var p_queue_dist = __nccwpck_require__(6459); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js + + + +const STATUS_NO_RETRY = [ + 400, // Bad Request + 401, // Unauthorized + 403, // Forbidden + 404, // Not Found + 405, // Method Not Allowed + 406, // Not Acceptable + 407, // Proxy Authentication Required + 408, // Request Timeout +]; +const STATUS_IGNORE = [ + 409, // Conflict +]; +/** + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. + */ +class AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async unshareRun(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - await raiseForStatus(response, "unshare run", true); - } - async readRunSharedLink(runId) { - assertUuid(runId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return undefined; + Object.defineProperty(this, "onFailedResponseHook", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.debug = params.debug; + if ( true) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist["default"]({ + concurrency: this.maxConcurrency, + }); } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); + } + this.onFailedResponseHook = params?.onFailedResponseHook; } - async listSharedRuns(shareToken, { runIds, } = {}) { - const queryParams = new URLSearchParams({ - share_token: shareToken, - }); - if (runIds !== undefined) { - for (const runId of runIds) { - queryParams.append("id", runId); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + const onFailedResponseHook = this.onFailedResponseHook; + return this.queue.add(() => p_retry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; } + else { + throw new Error(error); + } + }), { + async onFailedAttempt(error) { + if (error.message.startsWith("Cancel") || + error.message.startsWith("TimeoutError") || + error.message.startsWith("AbortError")) { + throw error; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (error?.code === "ECONNABORTED") { + throw error; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const response = error?.response; + const status = response?.status; + if (status) { + if (STATUS_NO_RETRY.includes(+status)) { + throw error; + } + else if (STATUS_IGNORE.includes(+status)) { + return; + } + if (onFailedResponseHook) { + await onFailedResponseHook(response); + } + } + }, + // If needed we can change some of the defaults here, + // but they're quite sensible. + retries: this.maxRetries, + randomize: true, + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + // Note this doesn't cancel the underlying request, + // when available prefer to use the signal option of the underlying call + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); } - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const runs = await response.json(); - return runs; + return this.call(callable, ...args); } - async readDatasetSharedSchema(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); + fetch(...args) { + return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js +function isLangChainMessage( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +message) { + return typeof message?._getType === "function"; +} +function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content }, + }; + // Check for presence of keys in additional_kwargs + if (message?.additional_kwargs && + Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; + } + return converted; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js +// Relaxed UUID validation regex (allows any valid UUID format including nil UUIDs) +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +function assertUuid(str, which) { + // Use relaxed regex validation instead of strict uuid.validate() + // This allows edge cases like nil UUIDs or test UUIDs that might not pass strict validation + if (!UUID_REGEX.test(str)) { + const msg = which !== undefined + ? `Invalid UUID for ${which}: ${str}` + : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js +const warnedMessages = {}; +function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; + } +} + +// EXTERNAL MODULE: ./node_modules/semver/index.js +var semver = __nccwpck_require__(2088); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js + +function isVersionGreaterOrEqual(current_version, target_version) { + const current = parseVersion(current_version); + const target = parseVersion(target_version); + if (!current || !target) { + throw new Error("Invalid version format."); + } + return current.compare(target) >= 0; +} +function parsePromptIdentifier(identifier) { + if (!identifier || + identifier.split("/").length > 2 || + identifier.startsWith("/") || + identifier.endsWith("/") || + identifier.split(":").length > 2) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) { + throw new Error(`Invalid identifier format: ${identifier}`); } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; + return [owner, name, commit]; + } + else { + if (!ownerNamePart) { + throw new Error(`Invalid identifier format: ${identifier}`); } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + return ["-", ownerNamePart, commit]; + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js +function getErrorStackTrace(e) { + if (typeof e !== "object" || e == null) + return undefined; + if (!("stack" in e) || typeof e.stack !== "string") + return undefined; + let stack = e.stack; + const prevLine = `${e}`; + if (stack.startsWith(prevLine)) { + stack = stack.slice(prevLine.length); + } + if (stack.startsWith("\n")) { + stack = stack.slice(1); + } + return stack; +} +function printErrorStackTrace(e) { + const stack = getErrorStackTrace(e); + if (stack == null) + return; + console.error(stack); +} +/** + * LangSmithConflictError + * + * Represents an error that occurs when there's a conflict during an operation, + * typically corresponding to HTTP 409 status code responses. + * + * This error is thrown when an attempt to create or modify a resource conflicts + * with the current state of the resource on the server. Common scenarios include: + * - Attempting to create a resource that already exists + * - Trying to update a resource that has been modified by another process + * - Violating a uniqueness constraint in the data + * + * @extends Error + * + * @example + * try { + * await createProject("existingProject"); + * } catch (error) { + * if (error instanceof ConflictError) { + * console.log("A conflict occurred:", error.message); + * // Handle the conflict, e.g., by suggesting a different project name + * } else { + * // Handle other types of errors + * } + * } + * + * @property {string} name - Always set to 'ConflictError' for easy identification + * @property {string} message - Detailed error message including server response + * + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 + */ +class LangSmithConflictError extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; + this.name = "LangSmithConflictError"; + this.status = 409; } - async shareDataset(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; +} +/** + * Throws an appropriate error based on the response status and body. + * + * @param response - The fetch Response object + * @param context - Additional context to include in the error message (e.g., operation being performed) + * @throws {LangSmithConflictError} When the response status is 409 + * @throws {Error} For all other non-ok responses + */ +async function raiseForStatus(response, context, consume) { + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + let errorBody; + if (response.ok) { + if (consume) { + errorBody = await response.text(); } - const data = { - dataset_id: datasetId, - }; - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "PUT", - headers: this.headers, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; + return; } - async unshareDataset(datasetId) { - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "unshare dataset", true); + errorBody = await response.text(); + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; + if (response.status === 409) { + throw new LangSmithConflictError(fullMessage); } - async readSharedDataset(shareToken) { - assertUuid(shareToken); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + const err = new Error(fullMessage); + err.status = response.status; + throw err; +} +const ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; +class ConflictingEndpointsError extends Error { + constructor() { + super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT " + + "and LANGSMITH_RUNS_ENDPOINTS."); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: ERR_CONFLICTING_ENDPOINTS }); - const dataset = await response.json(); - return dataset; + this.name = "ConflictingEndpointsError"; // helpful in logs } - /** - * Get shared examples. - * - * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. - * @param {Object} [options] Additional options for listing the examples. - * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. - * @returns {Promise} The shared examples. - */ - async listSharedExamples(shareToken, options) { - const params = {}; - if (options?.exampleIds) { - params.id = options.exampleIds; +} +function isConflictingEndpointsError(err) { + return (typeof err === "object" && + err !== null && + err.code === ERR_CONFLICTING_ENDPOINTS); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +/* eslint-disable */ +// @ts-nocheck + +var LIMIT_REPLACE_NODE = "[...]"; +var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; +var arr = []; +var replacerStack = []; +const encoder = new TextEncoder(); +function defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER, + }; +} +function encodeString(str) { + return encoder.encode(str); +} +// Shared function to handle well-known types +function serializeWellKnownTypes(val) { + if (val && typeof val === "object" && val !== null) { + if (val instanceof Map) { + return Object.fromEntries(val); } - const urlParams = new URLSearchParams(); - Object.entries(params).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((v) => urlParams.append(key, v)); + else if (val instanceof Set) { + return Array.from(val); + } + else if (val instanceof Date) { + return val.toISOString(); + } + else if (val instanceof RegExp) { + return val.toString(); + } + else if (val instanceof Error) { + return { + name: val.name, + message: val.message, + }; + } + } + else if (typeof val === "bigint") { + return val.toString(); + } + return val; +} +// Default replacer function to handle well-known types +function createDefaultReplacer(userReplacer) { + return function (key, val) { + // Apply user replacer first if provided + if (userReplacer) { + const userResult = userReplacer.call(this, key, val); + // If user replacer returned undefined, fall back to our serialization + if (userResult !== undefined) { + return userResult; + } + } + // Fall back to our well-known type handling + return serializeWellKnownTypes(val); + }; +} +// Regular stringify +function serialize(obj, errorContext, replacer, spacer, options) { + try { + const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); + return encodeString(str); + } + catch (e) { + // Fall back to more complex stringify if circular reference + if (!e.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); + } + getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== + "true" && + console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); + if (typeof options === "undefined") { + options = defaultOptions(); + } + decirc(obj, "", 0, [], undefined, 0, options); + let res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); } else { - urlParams.append(key, value); + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); } - }); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const result = await response.json(); - if (!response.ok) { - if ("detail" in result) { - throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) - ? result.detail.join("\n") - : "Unspecified error"}`); + } + catch (_) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } + else { + part[0][part[1]] = part[2]; + } } - throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); } - return result.map((example) => ({ - ...example, - _hostUrl: this.getHostUrl(), - })); + return encodeString(res); } - async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const extra = projectExtra || {}; - if (metadata) { - extra["metadata"] = metadata; +} +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([parent, k, val, propertyDescriptor]); } - const body = { - name: projectName, - extra, - description, - }; - if (referenceDatasetId !== null) { - body["reference_dataset_id"] = referenceDatasetId; + else { + replacerStack.push([val, k, replace]); } - const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "create project"); - const result = await response.json(); - return result; } - async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { - const endpoint = `${this.apiUrl}/sessions/${projectId}`; - let extra = projectExtra; - if (metadata) { - extra = { ...(extra || {}), metadata }; - } - const body = { - name, - extra, - description, - end_time: endTime ? new Date(endTime).toISOString() : null, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update project"); - const result = await response.json(); - return result; + else { + parent[k] = replace; + arr.push([parent, k, val]); } - async hasProject({ projectId, projectName, }) { - // TODO: Add a head request - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); +} +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; } - else if (projectName !== undefined) { - params.append("name", projectName); + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options); + } } else { - throw new Error("Must provide projectName or projectId"); + // Handle well-known types before Object.keys iteration + val = serializeWellKnownTypes(val); + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - try { - const result = await response.json(); - if (!response.ok) { - return false; + stack.pop(); + } +} +// Stable-stringify +function compareFunction(a, b) { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} +function deterministicStringify(obj, replacer, spacer, options) { + if (typeof options === "undefined") { + options = defaultOptions(); + } + var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; + var res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer); + } + else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + } + } + catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); } - // If it's OK and we're querying by name, need to check the list is not empty - if (Array.isArray(result)) { - return result.length > 0; + else { + part[0][part[1]] = part[2]; } - // projectId querying - return true; - } - catch (e) { - return false; } } - async readProject({ projectId, projectName, includeStats, }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); + return res; +} +function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; + try { + if (typeof val.toJSON === "function") { + return; + } } - else if (projectName !== undefined) { - params.append("name", projectName); + catch (_) { + return; } - else { - throw new Error("Must provide projectName or projectId"); + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options); } - result = response[0]; } else { - result = response; + // Handle well-known types before Object.keys iteration + val = serializeWellKnownTypes(val); + // Create a temporary object in the required way + var tmp = {}; + var keys = Object.keys(val).sort(compareFunction); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + deterministicDecirc(val[key], key, i, stack, val, depth, options); + tmp[key] = val[key]; + } + if (typeof parent !== "undefined") { + arr.push([parent, k, val]); + parent[k] = tmp; + } + else { + return tmp; + } } - return result; + stack.pop(); + } +} +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues(replacer) { + replacer = + typeof replacer !== "undefined" + ? replacer + : function (k, v) { + return v; + }; + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } + } + } + return replacer.call(this, key, val); + }; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js + + + + + + + + + + + + + +function mergeRuntimeEnvIntoRun(run) { + const runtimeEnv = getRuntimeEnvironment(); + const envVars = getLangChainEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime, + }, + metadata: { + ...envVars, + ...(envVars.revision_id || ("revision_id" in run && run.revision_id) + ? { + revision_id: ("revision_id" in run ? run.revision_id : undefined) ?? + envVars.revision_id, + } + : {}), + ...metadata, + }, + }; + return run; +} +const getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? + getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === undefined) { + return undefined; } - async getProjectUrl({ projectId, projectName, }) { - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide either projectName or projectId"); - } - const project = await this.readProject({ projectId, projectName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) { + throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); } - async getDatasetUrl({ datasetId, datasetName, }) { - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - const dataset = await this.readDataset({ datasetId, datasetName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + return samplingRate; +}; +// utility functions +const isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); +}; +async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; - } - throw new Error("No projects found to resolve tenant."); + return result; +} +function trimQuotes(str) { + if (str === undefined) { + return undefined; } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, } = {}) { - const params = new URLSearchParams(); - if (projectIds !== undefined) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== undefined) { - params.append("name", name); - } - if (nameContains !== undefined) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== undefined) { - params.append("reference_dataset", referenceDatasetId); - } - else if (referenceDatasetName !== undefined) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName, - }); - params.append("reference_dataset", dataset.id); - } - if (referenceFree !== undefined) { - params.append("reference_free", referenceFree.toString()); - } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; + return str + .trim() + .replace(/^"(.*)"$/, "$1") + .replace(/^'(.*)'$/, "$1"); +} +const handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "30", 10) * 1000; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + // Return directly after calling this check + return true; } } - async deleteProject({ projectId, projectName, }) { - let projectId_; - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide projectName or projectId"); - } - else if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId === undefined) { - projectId_ = (await this.readProject({ projectName })).id; - } - else { - projectId_ = projectId; - } - assertUuid(projectId_); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); + // Fall back to existing status checks + return false; +}; +function _formatFeedbackScore(score) { + if (typeof score === "number") { + // Truncate at 4 decimal places + return Number(score.toFixed(4)); } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); + return score; +} +class AutoBatchQueue { + constructor() { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] }); - if (description) { - formData.append("description", description); - } - if (dataType) { - formData.append("data_type", dataType); - } - if (name) { - formData.append("name", name); - } - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "POST", - headers: this.headers, - body: formData, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 }); - await raiseForStatus(response, "upload CSV"); - const result = await response.json(); - return result; } - async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { - const body = { - name, - description, - extra: metadata ? { metadata } : undefined, - }; - if (dataType) { - body.data_type = dataType; - } - if (inputsSchema) { - body.inputs_schema_definition = inputsSchema; - } - if (outputsSchema) { - body.outputs_schema_definition = outputsSchema; - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + // Setting itemPromiseResolve is synchronous with promise creation: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise + itemPromiseResolve = resolve; }); - await raiseForStatus(response, "create dataset"); - const result = await response.json(); - return result; + const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; + this.items.push({ + action: item.action, + payload: item.item, + otelContext: item.otelContext, + apiKey: item.apiKey, + apiUrl: item.apiUrl, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + itemPromiseResolve: itemPromiseResolve, + itemPromise, + size, + }); + this.sizeBytes += size; + return itemPromise; } - async readDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - // limit to 1 result - const params = new URLSearchParams({ limit: "1" }); - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - assertUuid(datasetId); - path += `/${datasetId}`; - } - else if (datasetName !== undefined) { - params.append("name", datasetName); - } - else { - throw new Error("Must provide datasetName or datasetId"); + pop(upToSizeBytes) { + if (upToSizeBytes < 1) { + throw new Error("Number of bytes to pop off may not be less than 1."); } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); + const popped = []; + let poppedSizeBytes = 0; + // Pop items until we reach or exceed the size limit + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && + this.items.length > 0) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; } - result = response[0]; - } - else { - result = response; - } - return result; - } - async hasDataset({ datasetId, datasetName, }) { - try { - await this.readDataset({ datasetId, datasetName }); - return true; } - catch (e) { - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - e instanceof Error && - e.message.toLocaleLowerCase().includes("not found")) { - return false; - } - throw e; + // If there is an item on the queue we were unable to pop, + // just return it as a single batch. + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; } + return [ + popped.map((it) => ({ + action: it.action, + item: it.payload, + otelContext: it.otelContext, + apiKey: it.apiKey, + apiUrl: it.apiUrl, + })), + () => popped.forEach((it) => it.itemPromiseResolve()), + ]; } - async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { - let datasetId_ = datasetId; - if (datasetId_ === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); +} +// 20 MB +const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20_971_520; +const SERVER_INFO_REQUEST_TIMEOUT = 2500; +const DEFAULT_API_URL = "https://api.smith.langchain.com"; +class Client { + constructor(config = {}) { + Object.defineProperty(this, "apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "webUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchIngestCaller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "hideInputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "hideOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingSampleRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: new AutoBatchQueue() + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "langSmithToOTELTranslator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "multipartStreamingDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) { + this.apiUrl = this.apiUrl.slice(0, -1); } - else if (datasetId_ !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) { + this.webUrl = this.webUrl.slice(0, -1); } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + this.timeout_ms = config.timeout_ms ?? 90_000; + this.caller = new AsyncCaller({ + ...(config.callerOptions ?? {}), + debug: config.debug ?? this.debug, + }); + this.traceBatchConcurrency = + config.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) { + throw new Error("Trace batch concurrency must be positive."); } - const urlParams = new URLSearchParams({ - from_version: typeof fromVersion === "string" - ? fromVersion - : fromVersion.toISOString(), - to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), + this.debug = config.debug ?? this.debug; + this.batchIngestCaller = new AsyncCaller({ + maxRetries: 2, + maxConcurrency: this.traceBatchConcurrency, + ...(config.callerOptions ?? {}), + onFailedResponseHook: handle429, + debug: config.debug ?? this.debug, }); - const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); - return response; + this.hideInputs = + config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = + config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; + this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; + this.blockOnRootRunFinalization = + config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config.batchSizeBytesLimit; + this.fetchOptions = config.fetchOptions || {}; + this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + if (getOtelEnabled()) { + this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); + } } - async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { - const path = "/datasets"; - if (datasetId !== undefined) { - // do nothing + static getDefaultClientConfig() { + const apiKey = getLangSmithEnvironmentVariable("API_KEY"); + const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; + const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; + const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; + return { + apiUrl: apiUrl, + apiKey: apiKey, + webUrl: undefined, + hideInputs: hideInputs, + hideOutputs: hideOutputs, + }; + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; } - else if (datasetName !== undefined) { - datasetId = (await this.readDataset({ datasetName })).id; + else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; } - else { - throw new Error("Must provide either datasetName or datasetId"); + else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; } - const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); - const datasetText = await response.text(); - const dataset = datasetText - .trim() - .split("\n") - .map((line) => JSON.parse(line)); - return dataset; - } - async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit.toString(), - offset: offset.toString(), - }); - if (datasetIds !== undefined) { - for (const id_ of datasetIds) { - params.append("id", id_); - } + else if (this.apiUrl.includes("/api") && + !this.apiUrl.split(".", 1)[0].endsWith("api")) { + this.webUrl = this.apiUrl.replace("/api", ""); + return this.webUrl; } - if (datasetName !== undefined) { - params.append("name", datasetName); + else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return this.webUrl; } - if (datasetNameContains !== undefined) { - params.append("name_contains", datasetNameContains); + else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); + else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; + else { + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; } } - /** - * Update a dataset - * @param props The dataset details to update - * @returns The updated dataset - */ - async updateDataset(props) { - const { datasetId, datasetName, ...update } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + get headers() { + const headers = { + "User-Agent": `langsmith-js/${__version__}`, + }; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(update), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update dataset"); - return (await response.json()); + return headers; } - /** - * Updates a tag on a dataset. - * - * If the tag is already assigned to a different version of this dataset, - * the tag will be moved to the new version. The as_of parameter is used to - * determine which version of the dataset to apply the new tags to. - * - * It must be an exact version of the dataset to succeed. You can - * use the "readDatasetVersion" method to find the exact version - * to apply the tags to. - * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. - * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. - * @param params.asOf The timestamp of the dataset to apply the new tags to. - * @param params.tag The new tag to apply to the dataset. - */ - async updateDatasetTag(props) { - const { datasetId, datasetName, asOf, tag } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), - tag, - }), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "update dataset tags"); + _getPlatformEndpointPath(path) { + // Check if apiUrl already ends with /v1 or /v1/ to avoid double /v1/v1/ paths + const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; + return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; } - async deleteDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + async processInputs(inputs) { + if (this.hideInputs === false) { + return inputs; } - if (datasetId_ !== undefined) { - assertUuid(datasetId_); - path += `/${datasetId_}`; + if (this.hideInputs === true) { + return {}; } - else { - throw new Error("Must provide datasetName or datasetId"); + if (typeof this.hideInputs === "function") { + return this.hideInputs(inputs); } - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + return inputs; } - async indexDataset({ datasetId, datasetName, tag, }) { - let datasetId_ = datasetId; - if (!datasetId_ && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); + async processOutputs(outputs) { + if (this.hideOutputs === false) { + return outputs; } - else if (datasetId_ && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); + if (this.hideOutputs === true) { + return {}; } - else if (!datasetId_) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + if (typeof this.hideOutputs === "function") { + return this.hideOutputs(outputs); } - assertUuid(datasetId_); - const data = { - tag: tag, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "index dataset"); - await response.json(); + return outputs; } - /** - * Lets you run a similarity search query on a dataset. - * - * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. - * - * @param inputs The input on which to run the similarity search. Must have the - * same schema as the dataset. - * - * @param datasetId The dataset to search for similar examples. - * - * @param limit The maximum number of examples to return. Will return the top `limit` most - * similar examples in order of most similar to least similar. If no similar - * examples are found, random examples will be returned. - * - * @param filter A filter string to apply to the search. Only examples will be returned that - * match the filter string. Some examples of filters - * - * - eq(metadata.mykey, "value") - * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) - * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) - * - * @returns A list of similar examples. - * - * - * @example - * dataset_id = "123e4567-e89b-12d3-a456-426614174000" - * inputs = {"text": "How many people live in Berlin?"} - * limit = 5 - * examples = await client.similarExamples(inputs, dataset_id, limit) - */ - async similarExamples(inputs, datasetId, limit, { filter, } = {}) { - const data = { - limit: limit, - inputs: inputs, - }; - if (filter !== undefined) { - data["filter"] = filter; + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== undefined) { + runParams.inputs = await this.processInputs(runParams.inputs); } - assertUuid(datasetId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), + if (runParams.outputs !== undefined) { + runParams.outputs = await this.processOutputs(runParams.outputs); + } + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "fetch similar examples"); - const result = await response.json(); - return result["examples"]; + await raiseForStatus(response, `Failed to fetch ${path}`); + return response; } - async createExample(inputsOrUpdate, outputs, options) { - if (isExampleCreate(inputsOrUpdate)) { - if (outputs !== undefined || options !== undefined) { - throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + async _get(path, queryParams) { + const response = await this._getResponse(path, queryParams); + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = transform + ? transform(await response.json()) + : await response.json(); + if (items.length === 0) { + break; } + yield items; + if (items.length < limit) { + break; + } + offset += items.length; } - let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; - const datasetName_ = outputs - ? options?.datasetName - : inputsOrUpdate.dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); - let data; - if (!isExampleCreate(inputsOrUpdate)) { - data = { - inputs: inputsOrUpdate, - outputs, - created_at: createdAt_?.toISOString(), - id: options?.exampleId, - metadata: options?.metadata, - split: options?.split, - source_run_id: options?.sourceRunId, - use_source_run_io: options?.useSourceRunIO, - use_source_run_attachments: options?.useSourceRunAttachments, - attachments: options?.attachments, - }; - } - else { - data = inputsOrUpdate; - } - const response = await this._uploadExamplesMultipart(datasetId_, [data]); - const example = await this.readExample(response.example_ids?.[0] ?? v4()); - return example; } - async createExamples(propsOrUploads) { - if (Array.isArray(propsOrUploads)) { - if (propsOrUploads.length === 0) { - return []; + async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { + const bodyParams = body ? { ...body } : {}; + while (true) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { + method: requestMethod, + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(bodyParams), + }); + const responseBody = await response.json(); + if (!responseBody) { + break; } - const uploads = propsOrUploads; - let datasetId_ = uploads[0].dataset_id; - const datasetName_ = uploads[0].dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); + if (!responseBody[dataKey]) { + break; } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + yield responseBody[dataKey]; + const cursors = responseBody.cursors; + if (!cursors) { + break; } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + if (!cursors.next) { + break; } - const response = await this._uploadExamplesMultipart(datasetId_, uploads); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; - if (inputs === undefined) { - throw new Error("Must provide inputs when using legacy parameters"); - } - let datasetId_ = datasetId; - const datasetName_ = datasetName; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; + bodyParams.cursor = cursors.next; } - const formattedExamples = inputs.map((input, idx) => { - return { - dataset_id: datasetId_, - inputs: input, - outputs: outputs?.[idx], - metadata: metadata?.[idx], - split: splits?.[idx], - id: exampleIds?.[idx], - attachments: attachments?.[idx], - source_run_id: sourceRunIds?.[idx], - use_source_run_io: useSourceRunIOs?.[idx], - use_source_run_attachments: useSourceRunAttachments?.[idx], - }; - }); - const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); - } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); - } - return message; - }); - const finalOutput = isLangChainMessage(generations) - ? convertLangChainMessageToExample(generations) - : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); } - async readExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const rawExample = await this._get(path); - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type, - }; - return acc; - }, {}); + // Allows mocking for tests + _shouldSample() { + if (this.tracingSampleRate === undefined) { + return true; } - return example; + return Math.random() < this.tracingSampleRate; } - async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { - let datasetId_; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - datasetId_ = datasetId; - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - throw new Error("Must provide a datasetName or datasetId"); - } - const params = new URLSearchParams({ dataset: datasetId_ }); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const inlineS3Urls_ = inlineS3Urls ?? true; - params.append("inline_s3_urls", inlineS3Urls_.toString()); - if (exampleIds !== undefined) { - for (const id_ of exampleIds) { - params.append("id", id_); - } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === undefined) { + return runs; } - if (splits !== undefined) { - for (const split of splits) { - params.append("splits", split); + if (patch) { + const sampled = []; + for (const run of runs) { + if (!this.filteredPostUuids.has(run.trace_id)) { + sampled.push(run); + } + else if (run.id === run.trace_id) { + this.filteredPostUuids.delete(run.trace_id); + } } + return sampled; } - if (metadata !== undefined) { - const serializedMetadata = JSON.stringify(metadata); - params.append("metadata", serializedMetadata); - } - if (limit !== undefined) { - params.append("limit", limit.toString()); - } - if (offset !== undefined) { - params.append("offset", offset.toString()); - } - if (filter !== undefined) { - params.append("filter", filter); - } - if (includeAttachments === true) { - ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); - } - let i = 0; - for await (const rawExamples of this._getPaginated("/examples", params)) { - for (const rawExample of rawExamples) { - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type || undefined, - }; - return acc; - }, {}); + else { + // For new runs, sample at trace level to maintain consistency + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + // If we've already made a decision about this trace, follow it + if (this.filteredPostUuids.has(traceId)) { + continue; + } + // For new traces, apply sampling + if (run.id === traceId) { + if (this._shouldSample()) { + sampled.push(run); + } + else { + this.filteredPostUuids.add(traceId); + } + } + else { + // Child runs follow their trace's sampling decision + sampled.push(run); } - yield example; - i++; } - if (limit !== undefined && i >= limit) { + return sampled; + } + } + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return (this.batchSizeBytesLimit ?? + serverInfo.batch_ingest_config?.size_limit_bytes ?? + DEFAULT_BATCH_SIZE_LIMIT_BYTES); + } + async _getMultiPartSupport() { + const serverInfo = await this._ensureServerInfo(); + return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); + } + drainAutoBatchQueue(batchSizeLimit) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); + if (!batch.length) { + done(); break; } + const batchesByDestination = batch.reduce((acc, item) => { + const apiUrl = item.apiUrl ?? this.apiUrl; + const apiKey = item.apiKey ?? this.apiKey; + const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; + const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; + if (!acc[batchKey]) { + acc[batchKey] = []; + } + acc[batchKey].push(item); + return acc; + }, {}); + const batchPromises = []; + for (const [batchKey, batch] of Object.entries(batchesByDestination)) { + const batchPromise = this._processBatch(batch, { + apiUrl: batchKey === "default" ? undefined : batchKey.split("|")[0], + apiKey: batchKey === "default" ? undefined : batchKey.split("|")[1], + }); + batchPromises.push(batchPromise); + } + // Wait for all batches to complete, then call the overall done callback + const allBatchesPromise = Promise.all(batchPromises).finally(done); + promises.push(allBatchesPromise); } + return Promise.all(promises); } - async deleteExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); - } - async updateExample(exampleIdOrUpdate, update) { - let exampleId; - if (update) { - exampleId = exampleIdOrUpdate; + async _processBatch(batch, options) { + if (!batch.length) { + return; } - else { - exampleId = exampleIdOrUpdate.id; + try { + if (this.langSmithToOTELTranslator !== undefined) { + this._sendBatchToOTELTranslator(batch); + } + else { + const ingestParams = { + runCreates: batch + .filter((item) => item.action === "create") + .map((item) => item.item), + runUpdates: batch + .filter((item) => item.action === "update") + .map((item) => item.item), + }; + const serverInfo = await this._ensureServerInfo(); + if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { + await this.multipartIngestRuns(ingestParams, options); + } + else { + await this.batchIngestRuns(ingestParams, options); + } + } } - assertUuid(exampleId); - let updateToUse; - if (update) { - updateToUse = { id: exampleId, ...update }; + catch (e) { + console.error("Error exporting batch:", e); + } + } + _sendBatchToOTELTranslator(batch) { + if (this.langSmithToOTELTranslator !== undefined) { + const otelContextMap = new Map(); + const operations = []; + for (const item of batch) { + if (item.item.id && item.otelContext) { + otelContextMap.set(item.item.id, item.otelContext); + if (item.action === "create") { + operations.push({ + operation: "post", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item, + }); + } + else { + operations.push({ + operation: "patch", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item, + }); + } + } + } + this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); } - else { - updateToUse = exampleIdOrUpdate; + } + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = undefined; + item.item = mergeRuntimeEnvIntoRun(item.item); + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) { + // Rely on manual flushing in serverless environments + return itemPromise; } - let datasetId; - if (updateToUse.dataset_id !== undefined) { - datasetId = updateToUse.dataset_id; + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { + void this.drainAutoBatchQueue(sizeLimitBytes); } - else { - const example = await this.readExample(exampleId); - datasetId = example.dataset_id; + if (this.autoBatchQueue.items.length > 0) { + this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = undefined; + void this.drainAutoBatchQueue(sizeLimitBytes); + }, this.autoBatchAggregationDelayMs); } - return this._updateExamplesMultipart(datasetId, [updateToUse]); + return itemPromise; } - async updateExamples(update) { - // We will naively get dataset id from first example and assume it works for all - let datasetId; - if (update[0].dataset_id === undefined) { - const example = await this.readExample(update[0].id); - datasetId = example.dataset_id; + async _getServerInfo() { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/info`, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT), + ...this.fetchOptions, + }); + await raiseForStatus(response, "get server info"); + const json = await response.json(); + if (this.debug) { + console.log("\n=== LangSmith Server Configuration ===\n" + + JSON.stringify(json, null, 2) + + "\n"); } - else { - datasetId = update[0].dataset_id; + return json; + } + async _ensureServerInfo() { + if (this._getServerInfoPromise === undefined) { + this._getServerInfoPromise = (async () => { + if (this._serverInfo === undefined) { + try { + this._serverInfo = await this._getServerInfo(); + } + catch (e) { + console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e.status}. Falling back to batch operations and default limits.`); + } + } + return this._serverInfo ?? {}; + })(); } - return this._updateExamplesMultipart(datasetId, update); + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === undefined) { + this._getServerInfoPromise = undefined; + } + return serverInfo; + }); + } + async _getSettings() { + if (!this.settings) { + this.settings = this._get("/settings"); + } + return await this.settings; } /** - * Get dataset version by closest date or exact tag. - * - * Use this to resolve the nearest version to a given timestamp or for a given tag. - * - * @param options The options for getting the dataset version - * @param options.datasetId The ID of the dataset - * @param options.datasetName The name of the dataset - * @param options.asOf The timestamp of the dataset to retrieve - * @param options.tag The tag of the dataset to retrieve - * @returns The dataset version + * Flushes current queued traces. */ - async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { - let resolvedDatasetId; - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - resolvedDatasetId = dataset.id; - } - else { - resolvedDatasetId = datasetId; + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + await this.drainAutoBatchQueue(sizeLimitBytes); + } + _cloneCurrentOTELContext() { + const otel_trace = getOTELTrace(); + const otel_context = getOTELContext(); + if (this.langSmithToOTELTranslator !== undefined) { + const currentSpan = otel_trace.getActiveSpan(); + if (currentSpan) { + return otel_trace.setSpan(otel_context.active(), currentSpan); + } } - assertUuid(resolvedDatasetId); - if ((asOf && tag) || (!asOf && !tag)) { - throw new Error("Exactly one of asOf and tag must be specified."); + return undefined; + } + async createRun(run, options) { + if (!this._filterForSampling([run]).length) { + return; } - const params = new URLSearchParams(); - if (asOf !== undefined) { - params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + const headers = { + ...this.headers, + "Content-Type": "application/json", + }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await this.prepareRunCreateOrUpdateInputs({ + session_name, + ...run, + start_time: run.start_time ?? Date.now(), + }); + if (this.autoBatchTracing && + runCreate.trace_id !== undefined && + runCreate.dotted_order !== undefined) { + const otelContext = this._cloneCurrentOTELContext(); + void this.processRunOperation({ + action: "create", + item: runCreate, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + return; } - if (tag !== undefined) { - params.append("tag", tag); + const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate); + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { - method: "GET", - headers: { ...this.headers }, + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs`, { + method: "POST", + headers, + body: serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "read dataset version"); - return await response.json(); + await raiseForStatus(response, "create run", true); } - async listDatasetSplits({ datasetId, datasetName, asOf, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates, }, options) { + if (runCreates === undefined && runUpdates === undefined) { + return; } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); + let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); + let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; + } + else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; + const rawBatch = { + post: preparedCreateParams, + patch: preparedUpdateParams, + }; + if (!rawBatch.post.length && !rawBatch.patch.length) { + return; } - else { - datasetId_ = datasetId; + const batchChunks = { + post: [], + patch: [], + }; + for (const k of ["post", "patch"]) { + const key = k; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== undefined) { + // Type is wrong but this is a deprecated code path anyway + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); + } } - assertUuid(datasetId_); - const params = new URLSearchParams(); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post + .map((item) => item.id) + .concat(batchChunks.patch.map((item) => item.id)) + .join(","); + await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); } - const response = await this._get(`/datasets/${datasetId_}/splits`, params); - return response; } - async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); - } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const data = { - split_name: splitName, - examples: exampleIds.map((id) => { - assertUuid(id); - return id; - }), - remove, + async _postBatchIngestRuns(body, options) { + const headers = { + ...this.headers, + "Content-Type": "application/json", + Accept: "application/json", }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/batch`, { + method: "POST", + headers, + body: body, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update dataset splits", true); + await raiseForStatus(response, "batch create run", true); } /** - * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs */ - async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { - warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); - let run_; - if (typeof run === "string") { - run_ = await this.readRun(run, { loadChildRuns }); + async multipartIngestRuns({ runCreates, runUpdates, }, options) { + if (runCreates === undefined && runUpdates === undefined) { + return; } - else if (typeof run === "object" && "id" in run) { - run_ = run; + // transform and convert to dicts + const allAttachments = {}; + let preparedCreateParams = []; + for (const create of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); + if (preparedCreate.id !== undefined && + preparedCreate.attachments !== undefined) { + allAttachments[preparedCreate.id] = preparedCreate.attachments; + } + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); } - else { - throw new Error(`Invalid run type: ${typeof run}`); + let preparedUpdateParams = []; + for (const update of runUpdates ?? []) { + preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); } - if (run_.reference_example_id !== null && - run_.reference_example_id !== undefined) { - referenceExample = await this.readExample(run_.reference_example_id); + // require trace_id and dotted_order + const invalidRunCreate = preparedCreateParams.find((runCreate) => { + return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); + }); + if (invalidRunCreate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); } - const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); - const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); - return feedbacks[0]; - } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { - if (!runId && !projectId) { - throw new Error("One of runId or projectId must be provided"); + const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { + return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); + }); + if (invalidRunUpdate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); } - if (runId && projectId) { - throw new Error("Only one of runId or projectId can be provided"); + // combine post and patch dicts where possible + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; + } + else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; } - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {}, + if (preparedCreateParams.length === 0 && + preparedUpdateParams.length === 0) { + return; + } + // send the runs in multipart requests + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [ + ["post", preparedCreateParams], + ["patch", preparedUpdateParams], + ]) { + for (const originalPayload of payloads) { + // collect fields to be sent as separate parts + const { inputs, outputs, events, attachments, ...payload } = originalPayload; + const fields = { inputs, outputs, events }; + // encode the main run payload + const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { + type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip + }), + }); + // encode the fields we collected + for (const [key, value] of Object.entries(fields)) { + if (value === undefined) { + continue; + } + const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { + type: `application/json; length=${stringifiedValue.length}`, + }), + }); + } + // encode the attachments + if (payload.id !== undefined) { + const attachments = allAttachments[payload.id]; + if (attachments) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments)) { + let contentType; + let content; + if (Array.isArray(attachment)) { + [contentType, content] = attachment; + } + else { + contentType = attachment.mimeType; + content = attachment.data; + } + // Validate that the attachment name doesn't contain a '.' + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + + `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { + type: `${contentType}; length=${content.byteLength}`, + }), + }); + } + } + } + // compute context + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + } + } + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); + } + async _createNodeFetchBody(parts, boundary) { + // Create multipart form data manually using Blobs + const chunks = []; + for (const part of parts) { + // Add field boundary + chunks.push(new Blob([`--${boundary}\r\n`])); + chunks.push(new Blob([ + `Content-Disposition: form-data; name="${part.name}"\r\n`, + `Content-Type: ${part.payload.type}\r\n\r\n`, + ])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + // Add final boundary + chunks.push(new Blob([`--${boundary}--\r\n`])); + // Combine all chunks into a single Blob + const body = new Blob(chunks); + // Convert Blob to ArrayBuffer for compatibility + const arrayBuffer = await body.arrayBuffer(); + return arrayBuffer; + } + async _createMultipartStream(parts, boundary) { + const encoder = new TextEncoder(); + // Create a ReadableStream for streaming the multipart data + // Only do special handling if we're using node-fetch + const stream = new ReadableStream({ + async start(controller) { + // Helper function to write a chunk to the stream + const writeChunk = async (chunk) => { + if (typeof chunk === "string") { + controller.enqueue(encoder.encode(chunk)); + } + else { + controller.enqueue(chunk); + } + }; + // Write each part to the stream + for (const part of parts) { + // Write boundary and headers + await writeChunk(`--${boundary}\r\n`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); + await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); + // Write the payload + const payloadStream = part.payload.stream(); + const reader = payloadStream.getReader(); + try { + let result; + while (!(result = await reader.read()).done) { + controller.enqueue(result.value); + } + } + finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + // Write final boundary + await writeChunk(`--${boundary}--\r\n`); + controller.close(); + }, + }); + return stream; + } + async _sendMultipartRequest(parts, context, options) { + // Create multipart form data boundary + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const isNodeFetch = _globalFetchImplementationIsNodeFetch(); + const buildBuffered = () => this._createNodeFetchBody(parts, boundary); + const buildStream = () => this._createMultipartStream(parts, boundary); + const send = async (body) => { + const headers = { + ...this.headers, + "Content-Type": `multipart/form-data; boundary=${boundary}`, + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + return this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { + method: "POST", + headers, + body, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); }; - if (sourceRunId !== undefined && - feedback_source?.metadata !== undefined && - !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; + try { + let res; + let streamedAttempt = false; + // attempt stream only if not disabled and not using node-fetch + if (!isNodeFetch && !this.multipartStreamingDisabled) { + streamedAttempt = true; + res = await send(await buildStream()); + } + else { + res = await send(await buildBuffered()); + } + // if stream fails, fallback to buffered body + if ((!this.multipartStreamingDisabled || streamedAttempt) && + res.status === 422 && + (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { + console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. ` + + `This usually means the host does not support chunked uploads. ` + + `Retrying with a buffered upload for operation "${context}".`); + // Disable streaming for future requests + this.multipartStreamingDisabled = true; + // retry with fully-buffered body + res = await send(await buildBuffered()); + } + // raise if still failing + await raiseForStatus(res, "ingest multipart runs", true); + // eslint-disable-next-line @typescript-eslint/no-explicit-any } - if (feedback_source?.metadata !== undefined && - feedback_source.metadata["__run"]?.run_id !== undefined) { - assertUuid(feedback_source.metadata["__run"].run_id); + catch (e) { + console.warn(`${e.message.trim()}\n\nContext: ${context}`); } - const feedback = { - id: feedbackId ?? v4(), - run_id: runId, - key, - score: _formatFeedbackScore(score), - value, - correction, - comment, - feedback_source: feedback_source, - comparative_experiment_id: comparativeExperimentId, - feedbackConfig, - session_id: projectId, - }; - const url = `${this.apiUrl}/feedback`; - const response = await this.caller.call(_getFetchImplementation(this.debug), url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedback), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "create feedback", true); - return feedback; } - async updateFeedback(feedbackId, { score, value, correction, comment, }) { - const feedbackUpdate = {}; - if (score !== undefined && score !== null) { - feedbackUpdate["score"] = _formatFeedbackScore(score); + async updateRun(runId, run, options) { + assertUuid(runId); + if (run.inputs) { + run.inputs = await this.processInputs(run.inputs); } - if (value !== undefined && value !== null) { - feedbackUpdate["value"] = value; + if (run.outputs) { + run.outputs = await this.processOutputs(run.outputs); } - if (correction !== undefined && correction !== null) { - feedbackUpdate["correction"] = correction; + // TODO: Untangle types + const data = { ...run, id: runId }; + if (!this._filterForSampling([data], true).length) { + return; } - if (comment !== undefined && comment !== null) { - feedbackUpdate["comment"] = comment; + if (this.autoBatchTracing && + data.trace_id !== undefined && + data.dotted_order !== undefined) { + const otelContext = this._cloneCurrentOTELContext(); + if (run.end_time !== undefined && + data.parent_run_id === undefined && + this.blockOnRootRunFinalization && + !this.manualFlushMode) { + // Trigger batches as soon as a root trace ends and wait to ensure trace finishes + // in serverless environments. + await this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + return; + } + else { + void this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + } + return; } - assertUuid(feedbackId); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { + const headers = { + ...this.headers, + "Content-Type": "application/json", + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(feedbackUpdate), + headers, + body: serialize(run, `Serializing payload to update run with id: ${runId}`), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update feedback", true); - } - async readFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; + await raiseForStatus(response, "update run", true); } - async deleteFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `delete ${path}`); - await response.json(); + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns) { + run = await this._loadChildRuns(run); + } + return run; } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - queryParams.append("run", runIds.join(",")); + async getRunUrl({ runId, run, projectOpts, }) { + if (run !== undefined) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; + } + else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + } + else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; + } + else { + const project = await this.readProject({ + projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", + }); + sessionId = project.id; + } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); + else if (runId !== undefined) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); + else { + throw new Error("Must provide either runId or run"); + } + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id, + })); + const treemap = {}; + const runs = {}; + // TODO: make dotted order required when the migration finishes + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || + childRun.parent_run_id === undefined) { + throw new Error(`Child run ${childRun.id} has no parent`); + } + if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && + childRun.id !== run.id) { + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; } } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; + } } + return run; } /** - * Creates a presigned feedback token and URL. + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. * - * The token can be used to authorize feedback metrics without - * needing an API key. This is useful for giving browser-based - * applications the ability to submit feedback without needing - * to expose an API key. + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); * - * @param runId The ID of the run. - * @param feedbackKey The feedback key. - * @param options Additional options for the token. - * @param options.expiration The expiration time for the token. + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); * - * @returns A promise that resolves to a FeedbackIngestToken. + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); */ - async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { - const body = { - run_id: runId, - feedback_key: feedbackKey, - feedback_config: feedbackConfig, - }; - if (expiration) { - if (typeof expiration === "string") { - body["expires_at"] = expiration; - } - else if (expiration?.hours || expiration?.minutes || expiration?.days) { - body["expires_in"] = expiration; - } - } - else { - body["expires_in"] = { - hours: 3, - }; - } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - const result = await response.json(); - return result; - } - async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { - if (experimentIds.length === 0) { - throw new Error("At least one experiment is required"); - } - if (!referenceDatasetId) { - referenceDatasetId = (await this.readProject({ - projectId: experimentIds[0], - })).reference_dataset_id; + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; + let projectIds = []; + if (projectId) { + projectIds = Array.isArray(projectId) ? projectId : [projectId]; } - if (!referenceDatasetId == null) { - throw new Error("A reference dataset is required"); + if (projectName) { + const projectNames = Array.isArray(projectName) + ? projectName + : [projectName]; + const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); + projectIds.push(...projectIds_); } + const default_select = [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id", + ]; const body = { + session: projectIds.length ? projectIds : null, + run_type: runType, + reference_example: referenceExampleId, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + execution_order: executionOrder, + parent_run: parentRunId, + start_time: startTime ? startTime.toISOString() : null, + error, id, - name, - experiment_ids: experimentIds, - reference_dataset_id: referenceDatasetId, - description, - created_at: (createdAt ?? new Date())?.toISOString(), - extra: {}, + limit, + trace: traceId, + select: select ? select : default_select, + is_root: isRoot, + order, }; - if (metadata) - body.extra["metadata"] = metadata; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - return await response.json(); - } - /** - * Retrieves a list of presigned feedback tokens for a given run ID. - * @param runId The ID of the run. - * @returns An async iterable of FeedbackIngestToken objects. - */ - async *listPresignedFeedbackTokens(runId) { - assertUuid(runId); - const params = new URLSearchParams({ run_id: runId }); - for await (const tokens of this._getPaginated("/feedback/tokens", params)) { - yield* tokens; - } - } - _selectEvalResults(results) { - let results_; - if ("results" in results) { - results_ = results.results; - } - else if (Array.isArray(results)) { - results_ = results; - } - else { - results_ = [results]; - } - return results_; - } - async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const evalResults = this._selectEvalResults(evaluatorResponse); - const feedbacks = []; - for (const res of evalResults) { - let sourceInfo_ = sourceInfo || {}; - if (res.evaluatorInfo) { - sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; - } - let runId_ = null; - if (res.targetRunId) { - runId_ = res.targetRunId; + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + if (limit) { + if (runsYielded >= limit) { + break; + } + if (runs.length + runsYielded > limit) { + const newRuns = runs.slice(0, limit - runsYielded); + yield* newRuns; + break; + } + runsYielded += runs.length; + yield* runs; } - else if (run) { - runId_ = run.id; + else { + yield* runs; } - feedbacks.push(await this.createFeedback(runId_, res.key, { - score: res.score, - value: res.value, - comment: res.comment, - correction: res.correction, - sourceInfo: sourceInfo_, - sourceRunId: res.sourceRunId, - feedbackConfig: res.feedbackConfig, - feedbackSourceType: "model", - })); } - return [evalResults, feedbacks]; - } - async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); - return results; } - /** - * API for managing annotation queues - */ - /** - * List the annotation queues on the LangSmith API. - * @param options - The options for listing annotation queues - * @param options.queueIds - The IDs of the queues to filter by - * @param options.name - The name of the queue to filter by - * @param options.nameContains - The substring that the queue name should contain - * @param options.limit - The maximum number of queues to return - * @returns An iterator of AnnotationQueue objects - */ - async *listAnnotationQueues(options = {}) { - const { queueIds, name, nameContains, limit } = options; - const params = new URLSearchParams(); - if (queueIds) { - queueIds.forEach((id, i) => { - assertUuid(id, `queueIds[${i}]`); - params.append("ids", id); + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; + const sessionId = projectId || (await this.readProject({ projectName })).id; + const baseBody = { + session_id: sessionId, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100, + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset, + }; + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); + const response = await this.caller.call(_getFetchImplementation(), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - } - if (name) - params.append("name", name); - if (nameContains) - params.append("name_contains", nameContains); - params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); - let count = 0; - for await (const queues of this._getPaginated("/annotation-queues", params)) { - yield* queues; - count++; - if (limit !== undefined && count >= limit) + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = await response.json(); + const { groups, total } = items; + if (groups.length === 0) { + break; + } + for (const thread of groups) { + yield thread; + } + currentOffset += groups.length; + if (currentOffset >= total) { break; + } } } - /** - * Create an annotation queue on the LangSmith API. - * @param options - The options for creating an annotation queue - * @param options.name - The name of the annotation queue - * @param options.description - The description of the annotation queue - * @param options.queueId - The ID of the annotation queue - * @returns The created AnnotationQueue object - */ - async createAnnotationQueue(options) { - const { name, description, queueId, rubricInstructions } = options; - const body = { - name, - description, - id: queueId || v4(), - rubric_instructions: rubricInstructions, + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { + let projectIds_ = projectIds || []; + if (projectNames) { + projectIds_ = [ + ...(projectIds || []), + ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), + ]; + } + const payload = { + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType, }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))), + headers: this.headers, + body: JSON.stringify(filteredPayload), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create annotation queue"); - const data = await response.json(); - return data; + const result = await response.json(); + return result; } - /** - * Read an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to read - * @returns The AnnotationQueueWithDetails object - */ - async readAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "GET", + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4(), + }; + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", headers: this.headers, + body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "read annotation queue"); - const data = await response.json(); - return data; + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } - /** - * Update an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to update - * @param options - The options for updating the annotation queue - * @param options.name - The new name for the annotation queue - * @param options.description - The new description for the annotation queue - */ - async updateAnnotationQueue(queueId, options) { - const { name, description, rubricInstructions } = options; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - name, - description, - rubric_instructions: rubricInstructions, - }), + async unshareRun(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "update annotation queue"); + await raiseForStatus(response, "unshare run", true); } - /** - * Delete an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to delete - */ - async deleteAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, + async readRunSharedLink(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "delete annotation queue"); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return undefined; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; } - /** - * Add runs to an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue - * @param runIds - The IDs of the runs to be added to the annotation queue - */ - async addRunsToAnnotationQueue(queueId, runIds) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), + async listSharedRuns(shareToken, { runIds, } = {}) { + const queryParams = new URLSearchParams({ + share_token: shareToken, + }); + if (runIds !== undefined) { + for (const runId of runIds) { + queryParams.append("id", runId); + } + } + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "add runs to annotation queue"); + const runs = await response.json(); + return runs; } - /** - * Get a run from an annotation queue at the specified index. - * @param queueId - The ID of the annotation queue - * @param index - The index of the run to retrieve - * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object - * @throws {Error} If the run is not found at the given index or for other API-related errors - */ - async getRunFromAnnotationQueue(queueId, index) { - const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index}`, { + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "get run from annotation queue"); - return await response.json(); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; } - /** - * Delete a run from an an annotation queue. - * @param queueId - The ID of the annotation queue to delete the run from - * @param queueRunId - The ID of the run to delete from the annotation queue - */ - async deleteRunFromAnnotationQueue(queueId, queueRunId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + async shareDataset(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + const data = { + dataset_id: datasetId, + }; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, + headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "delete run from annotation queue"); + await raiseForStatus(response, "unshare dataset", true); } - /** - * Get the size of an annotation queue. - * @param queueId - The ID of the annotation queue - */ - async getSizeFromAnnotationQueue(queueId) { - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + async readSharedDataset(shareToken) { + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "get size from annotation queue"); - return await response.json(); - } - async _currentTenantIsOwner(owner) { - const settings = await this._getSettings(); - return owner == "-" || settings.tenant_handle === owner; - } - async _ownerConflictError(action, owner) { - const settings = await this._getSettings(); - return new Error(`Cannot ${action} for another tenant.\n - Current tenant: ${settings.tenant_handle}\n - Requested tenant: ${owner}`); + const dataset = await response.json(); + return dataset; } - async _getLatestCommitHash(promptOwnerAndName) { - const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) { + params.id = options.exampleIds; + } + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => urlParams.append(key, v)); + } + else { + urlParams.append(key, value); + } + }); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - const json = await res.json(); - if (!res.ok) { - const detail = typeof json.detail === "string" - ? json.detail - : JSON.stringify(json.detail); - const error = new Error(`Error ${res.status}: ${res.statusText}\n${detail}`); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - error.statusCode = res.status; - throw error; - } - if (json.commits.length === 0) { - return undefined; + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) { + throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) + ? result.detail.join("\n") + : "Unspecified error"}`); + } + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); } - return json.commits[0].commit_hash; + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl(), + })); } - async _likeOrUnlikePrompt(promptIdentifier, like) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { + async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { + const upsert_ = upsert ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const extra = projectExtra || {}; + if (metadata) { + extra["metadata"] = metadata; + } + const body = { + name: projectName, + extra, + description, + }; + if (referenceDatasetId !== null) { + body["reference_dataset_id"] = referenceDatasetId; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { method: "POST", - body: JSON.stringify({ like: like }), headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); - return await response.json(); + await raiseForStatus(response, "create project"); + const result = await response.json(); + return result; } - async _getPromptUrl(promptIdentifier) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - if (commitHash !== "latest") { - return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; - } - else { - return `${this.getHostUrl()}/hub/${owner}/${promptName}`; - } + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) { + extra = { ...(extra || {}), metadata }; + } + const body = { + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update project"); + const result = await response.json(); + return result; + } + async hasProject({ projectId, projectName, }) { + // TODO: Add a head request + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); } else { - const settings = await this._getSettings(); - if (commitHash !== "latest") { - return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + throw new Error("Must provide projectName or projectId"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + try { + const result = await response.json(); + if (!response.ok) { + return false; } - else { - return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + // If it's OK and we're querying by name, need to check the list is not empty + if (Array.isArray(result)) { + return result.length > 0; } + // projectId querying + return true; + } + catch (e) { + return false; } } - async promptExists(promptIdentifier) { - const prompt = await this.getPrompt(promptIdentifier); - return !!prompt; + async readProject({ projectId, projectName, includeStats, }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); + } + else { + throw new Error("Must provide projectName or projectId"); + } + if (includeStats !== undefined) { + params.append("include_stats", includeStats.toString()); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; + } + else { + result = response; + } + return result; } - async likePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, true); + async getProjectUrl({ projectId, projectName, }) { + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide either projectName or projectId"); + } + const project = await this.readProject({ projectId, projectName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; } - async unlikePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, false); + async getDatasetUrl({ datasetId, datasetName, }) { + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + const dataset = await this.readDataset({ datasetId, datasetName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; } - async *listCommits(promptOwnerAndName) { - for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { - yield* commits; + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; + } + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; } + throw new Error("No projects found to resolve tenant."); } - async *listPrompts(options) { + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, } = {}) { const params = new URLSearchParams(); - params.append("sort_field", options?.sortField ?? "updated_at"); - params.append("sort_direction", "desc"); - params.append("is_archived", (!!options?.isArchived).toString()); - if (options?.isPublic !== undefined) { - params.append("is_public", options.isPublic.toString()); + if (projectIds !== undefined) { + for (const projectId of projectIds) { + params.append("id", projectId); + } } - if (options?.query) { - params.append("query", options.query); + if (name !== undefined) { + params.append("name", name); } - for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { - yield* prompts; + if (nameContains !== undefined) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== undefined) { + params.append("reference_dataset", referenceDatasetId); + } + else if (referenceDatasetName !== undefined) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName, + }); + params.append("reference_dataset", dataset.id); + } + if (referenceFree !== undefined) { + params.append("reference_free", referenceFree.toString()); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; } } - async getPrompt(promptIdentifier) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - if (response.status === 404) { - return null; + async deleteProject({ projectId, projectName, }) { + let projectId_; + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide projectName or projectId"); } - await raiseForStatus(response, "get prompt"); - const result = await response.json(); - if (result.repo) { - return result.repo; + else if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId === undefined) { + projectId_ = (await this.readProject({ projectName })).id; } else { - return null; + projectId_ = projectId; } + assertUuid(projectId_); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); } - async createPrompt(promptIdentifier, options) { - const settings = await this._getSettings(); - if (options?.isPublic && !settings.tenant_handle) { - throw new Error(`Cannot create a public prompt without first\n - creating a LangChain Hub handle. - You can add a handle by creating a public prompt at:\n - https://smith.langchain.com/prompts`); + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("create a prompt", owner); + if (dataType) { + formData.append("data_type", dataType); } - const data = { - repo_handle: promptName, - ...(options?.description && { description: options.description }), - ...(options?.readme && { readme: options.readme }), - ...(options?.tags && { tags: options.tags }), - is_public: !!options?.isPublic, - }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { + if (name) { + formData.append("name", name); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(data), + headers: this.headers, + body: formData, signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create prompt"); - const { repo } = await response.json(); - return repo; + await raiseForStatus(response, "upload CSV"); + const result = await response.json(); + return result; } - async createCommit(promptIdentifier, object, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash - ? await this._getLatestCommitHash(`${owner}/${promptName}`) - : options?.parentCommitHash; - const payload = { - manifest: JSON.parse(JSON.stringify(object)), - parent_commit: resolvedParentCommitHash, + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { + const body = { + name, + description, + extra: metadata ? { metadata } : undefined, }; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { + if (dataType) { + body.data_type = dataType; + } + if (inputsSchema) { + body.inputs_schema_definition = inputsSchema; + } + if (outputsSchema) { + body.outputs_schema_definition = outputsSchema; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify(payload), + body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms), ...this.fetchOptions, }); - await raiseForStatus(response, "create commit"); + await raiseForStatus(response, "create dataset"); const result = await response.json(); - return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); - } - /** - * Update examples with attachments using multipart form data. - * @param updates List of ExampleUpdateWithAttachments objects to upsert - * @returns Promise with the update response - */ - async updateExamplesMultipart(datasetId, updates = []) { - return this._updateExamplesMultipart(datasetId, updates); + return result; } - async _updateExamplesMultipart(datasetId, updates = []) { - if (!(await this._getMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + async readDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + // limit to 1 result + const params = new URLSearchParams({ limit: "1" }); + if (datasetId && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - const formData = new FormData(); - for (const example of updates) { - const exampleId = example.id; - // Prepare the main example body - const exampleBody = { - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - if (example.attachments_operations) { - const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); - const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { - type: "application/json", - }); - formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + else if (datasetId) { + assertUuid(datasetId); + path += `/${datasetId}`; + } + else if (datasetName) { + params.append("name", datasetName); + } + else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); } + result = response[0]; + } + else { + result = response; } - const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetIdToUse}/examples`, { - method: "PATCH", - headers: this.headers, - body: formData, - }); - const result = await response.json(); return result; } - /** - * Upload examples with attachments using multipart form data. - * @param uploads List of ExampleUploadWithAttachments objects to upload - * @returns Promise with the upload response - * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead - */ - async uploadExamplesMultipart(datasetId, uploads = []) { - return this._uploadExamplesMultipart(datasetId, uploads); - } - async _uploadExamplesMultipart(datasetId, uploads = []) { - if (!(await this._getMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + async hasDataset({ datasetId, datasetName, }) { + try { + await this.readDataset({ datasetId, datasetName }); + return true; } - const formData = new FormData(); - for (const example of uploads) { - const exampleId = (example.id ?? v4()).toString(); - // Prepare the main example body - const exampleBody = { - created_at: example.created_at, - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - ...(example.source_run_id && { source_run_id: example.source_run_id }), - ...(example.use_source_run_io && { - use_source_run_io: example.use_source_run_io, - }), - ...(example.use_source_run_attachments && { - use_source_run_attachments: example.use_source_run_attachments, - }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } + catch (e) { + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + e instanceof Error && + e.message.toLocaleLowerCase().includes("not found")) { + return false; } + throw e; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/v1/platform/datasets/${datasetId}/examples`, { - method: "POST", - headers: this.headers, - body: formData, - }); - await raiseForStatus(response, "upload examples"); - const result = await response.json(); - return result; } - async updatePrompt(promptIdentifier, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); + async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { + let datasetId_ = datasetId; + if (datasetId_ === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - const [owner, promptName] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("update a prompt", owner); + else if (datasetId_ !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - const payload = {}; - if (options?.description !== undefined) - payload.description = options.description; - if (options?.readme !== undefined) - payload.readme = options.readme; - if (options?.tags !== undefined) - payload.tags = options.tags; - if (options?.isPublic !== undefined) - payload.is_public = options.isPublic; - if (options?.isArchived !== undefined) - payload.is_archived = options.isArchived; - // Check if payload is empty - if (Object.keys(payload).length === 0) { - throw new Error("No valid update options provided"); + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "PATCH", - body: JSON.stringify(payload), - headers: { - ...this.headers, - "Content-Type": "application/json", - }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" + ? fromVersion + : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), }); - await raiseForStatus(response, "update prompt"); - return response.json(); + const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + return response; } - async deletePrompt(promptIdentifier) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); + async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { + const path = "/datasets"; + if (datasetId !== undefined) { + // do nothing } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("delete a prompt", owner); + else if (datasetName !== undefined) { + datasetId = (await this.readDataset({ datasetName })).id; } - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - return await response.json(); - } - async pullPromptCommit(promptIdentifier, options) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, "pull prompt commit"); - const result = await response.json(); - return { - owner, - repo: promptName, - commit_hash: result.commit_hash, - manifest: result.manifest, - examples: result.examples, - }; + else { + throw new Error("Must provide either datasetName or datasetId"); + } + const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); + const datasetText = await response.text(); + const dataset = datasetText + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + return dataset; } - /** - * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. - * Using this method directly returns the JSON string of the prompt rather than a LangChain object. - * @private - */ - async _pullPrompt(promptIdentifier, options) { - const promptObject = await this.pullPromptCommit(promptIdentifier, { - includeModel: options?.includeModel, + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString(), }); - const prompt = JSON.stringify(promptObject.manifest); - return prompt; - } - async pushPrompt(promptIdentifier, options) { - // Create or update prompt metadata - if (await this.promptExists(promptIdentifier)) { - if (options && Object.keys(options).some((key) => key !== "object")) { - await this.updatePrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); + if (datasetIds !== undefined) { + for (const id_ of datasetIds) { + params.append("id", id_); } } - else { - await this.createPrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); + if (datasetName !== undefined) { + params.append("name", datasetName); } - if (!options?.object) { - return await this._getPromptUrl(promptIdentifier); + if (datasetNameContains !== undefined) { + params.append("name_contains", datasetNameContains); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; } - // Create a commit with the new manifest - const url = await this.createCommit(promptIdentifier, options?.object, { - parentCommitHash: options?.parentCommitHash, - }); - return url; } /** - * Clone a public dataset to your own langsmith tenant. - * This operation is idempotent. If you already have a dataset with the given name, - * this function will do nothing. - - * @param {string} tokenOrUrl The token of the public dataset to clone. - * @param {Object} [options] Additional options for cloning the dataset. - * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. - * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. - * @returns {Promise} + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset */ - async clonePublicDataset(tokenOrUrl, options = {}) { - const { sourceApiUrl = this.apiUrl, datasetName } = options; - const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); - const sourceClient = new Client({ - apiUrl: parsedApiUrl, - // Placeholder API key not needed anymore in most cases, but - // some private deployments may have API key-based rate limiting - // that would cause this to fail if we provide no value. - apiKey: "placeholder", - }); - const ds = await sourceClient.readSharedDataset(tokenUuid); - const finalDatasetName = datasetName || ds.name; - try { - if (await this.hasDataset({ datasetId: finalDatasetName })) { - console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); - return; - } + async updateDataset(props) { + const { datasetId, datasetName, ...update } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - catch (_) { - // `.hasDataset` will throw an error if the dataset does not exist. - // no-op in that case + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(update), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update dataset"); + return (await response.json()); + } + /** + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. + */ + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - // Fetch examples first, then create the dataset - const examples = await sourceClient.listSharedExamples(tokenUuid); - const dataset = await this.createDataset(finalDatasetName, { - description: ds.description, - dataType: ds.data_type || "kv", - inputsSchema: ds.inputs_schema_definition ?? undefined, - outputsSchema: ds.outputs_schema_definition ?? undefined, + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag, + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - try { - await this.createExamples({ - inputs: examples.map((e) => e.inputs), - outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), - datasetId: dataset.id, - }); + await raiseForStatus(response, "update dataset tags"); + } + async deleteDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - catch (e) { - console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + - "You should delete it manually."); - throw e; + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } - } - parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { - // Try parsing as UUID - try { - assertUuid(urlOrToken); // Will throw if it's not a UUID. - return [apiUrl, urlOrToken]; + if (datasetId_ !== undefined) { + assertUuid(datasetId_); + path += `/${datasetId_}`; } - catch (_) { - // no-op if it's not a uuid + else { + throw new Error("Must provide datasetName or datasetId"); } - // Parse as URL - try { - const parsedUrl = new URL(urlOrToken); - const pathParts = parsedUrl.pathname - .split("/") - .filter((part) => part !== ""); - if (pathParts.length >= numParts) { - const tokenUuid = pathParts[pathParts.length - numParts]; - return [apiUrl, tokenUuid]; - } - else { - throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); - } + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async indexDataset({ datasetId, datasetName, tag, }) { + let datasetId_ = datasetId; + if (!datasetId_ && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); } - catch (error) { - throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); + else if (datasetId_ && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (!datasetId_) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } + assertUuid(datasetId_); + const data = { + tag: tag, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "index dataset"); + await response.json(); } /** - * Awaits all pending trace batches. Useful for environments where - * you need to be sure that all tracing requests finish before execution ends, - * such as serverless environments. + * Lets you run a similarity search query on a dataset. * - * @example - * ``` - * import { Client } from "langsmith"; + * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. * - * const client = new Client(); + * @param inputs The input on which to run the similarity search. Must have the + * same schema as the dataset. * - * try { - * // Tracing happens here - * ... - * } finally { - * await client.awaitPendingTraceBatches(); - * } - * ``` + * @param datasetId The dataset to search for similar examples. * - * @returns A promise that resolves once all currently pending traces have sent. + * @param limit The maximum number of examples to return. Will return the top `limit` most + * similar examples in order of most similar to least similar. If no similar + * examples are found, random examples will be returned. + * + * @param filter A filter string to apply to the search. Only examples will be returned that + * match the filter string. Some examples of filters + * + * - eq(metadata.mykey, "value") + * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) + * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) + * + * @returns A list of similar examples. + * + * + * @example + * dataset_id = "123e4567-e89b-12d3-a456-426614174000" + * inputs = {"text": "How many people live in Berlin?"} + * limit = 5 + * examples = await client.similarExamples(inputs, dataset_id, limit) */ - awaitPendingTraceBatches() { - if (this.manualFlushMode) { - console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); - return Promise.resolve(); - } - return Promise.all([ - ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), - this.batchIngestCaller.queue.onIdle(), - ]); - } -} -function isExampleCreate(input) { - return "dataset_id" in input || "dataset_name" in input; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js - - - -// Update using yarn bump-version -const __version__ = "0.3.31"; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js -// Inlined from https://github.com/flexdinesh/browser-or-node - -let globalEnv; -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !isDeno(); -const getEnv = () => { - if (globalEnv) { - return globalEnv; - } - if (isBrowser()) { - globalEnv = "browser"; - } - else if (isNode()) { - globalEnv = "node"; - } - else if (isWebWorker()) { - globalEnv = "webworker"; - } - else if (isJsDom()) { - globalEnv = "jsdom"; - } - else if (isDeno()) { - globalEnv = "deno"; - } - else { - globalEnv = "other"; - } - return globalEnv; -}; -let runtimeEnvironment; -function getRuntimeEnvironment() { - if (runtimeEnvironment === undefined) { - const env = getEnv(); - const releaseEnv = getShas(); - runtimeEnvironment = { - library: "langsmith", - runtime: env, - sdk: "langsmith-js", - sdk_version: __version__, - ...releaseEnv, + async similarExamples(inputs, datasetId, limit, { filter, } = {}) { + const data = { + limit: limit, + inputs: inputs, }; - } - return runtimeEnvironment; -} -/** - * Retrieves the LangChain-specific environment variables from the current runtime environment. - * Sensitive keys (containing the word "key", "token", or "secret") have their values redacted for security. - * - * @returns {Record} - * - A record of LangChain-specific environment variables. - */ -function getLangChainEnvVars() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - for (const [key, value] of Object.entries(allEnvVars)) { - if (key.startsWith("LANGCHAIN_") && typeof value === "string") { - envVars[key] = value; + if (filter !== undefined) { + data["filter"] = filter; } + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "fetch similar examples"); + const result = await response.json(); + return result["examples"]; } - for (const key in envVars) { - if ((key.toLowerCase().includes("key") || - key.toLowerCase().includes("secret") || - key.toLowerCase().includes("token")) && - typeof envVars[key] === "string") { - const value = envVars[key]; - envVars[key] = - value.slice(0, 2) + "*".repeat(value.length - 4) + value.slice(-2); + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== undefined || options !== undefined) { + throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + } + } + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs + ? options?.datasetName + : inputsOrUpdate.dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) { + data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments, + }; + } + else { + data = inputsOrUpdate; } + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + const example = await this.readExample(response.example_ids?.[0] ?? v4()); + return example; } - return envVars; -} -/** - * Retrieves the LangChain-specific metadata from the current runtime environment. - * - * @returns {Record} - * - A record of LangChain-specific metadata environment variables. - */ -function getLangChainEnvVarsMetadata() { - const allEnvVars = getEnvironmentVariables() || {}; - const envVars = {}; - const excluded = [ - "LANGCHAIN_API_KEY", - "LANGCHAIN_ENDPOINT", - "LANGCHAIN_TRACING_V2", - "LANGCHAIN_PROJECT", - "LANGCHAIN_SESSION", - "LANGSMITH_API_KEY", - "LANGSMITH_ENDPOINT", - "LANGSMITH_TRACING_V2", - "LANGSMITH_PROJECT", - "LANGSMITH_SESSION", - ]; - for (const [key, value] of Object.entries(allEnvVars)) { - if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && - typeof value === "string" && - !excluded.includes(key) && - !key.toLowerCase().includes("key") && - !key.toLowerCase().includes("secret") && - !key.toLowerCase().includes("token")) { - if (key === "LANGCHAIN_REVISION_ID") { - envVars["revision_id"] = value; + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) { + return []; } - else { - envVars[key] = value; + const uploads = propsOrUploads; + let datasetId_ = uploads[0].dataset_id; + const datasetName_ = uploads[0].dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; } + const response = await this._uploadExamplesMultipart(datasetId_, uploads); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; } - } - return envVars; -} -/** - * Retrieves the environment variables from the current runtime environment. - * - * This function is designed to operate in a variety of JS environments, - * including Node.js, Deno, browsers, etc. - * - * @returns {Record | undefined} - * - A record of environment variables if available. - * - `undefined` if the environment does not support or allows access to environment variables. - */ -function getEnvironmentVariables() { - try { - // Check for Node.js environment - // eslint-disable-next-line no-process-env - if (typeof process !== "undefined" && process.env) { - // eslint-disable-next-line no-process-env - return Object.entries(process.env).reduce((acc, [key, value]) => { - acc[key] = String(value); - return acc; - }, {}); + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; + if (inputs === undefined) { + throw new Error("Must provide inputs when using legacy parameters"); } - // For browsers and other environments, we may not have direct access to env variables - // Return undefined or any other fallback as required. - return undefined; - } - catch (e) { - // Catch any errors that might occur while trying to access environment variables - return undefined; - } -} -function getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; - } - catch (e) { - return undefined; - } -} -function getLangSmithEnvironmentVariable(name) { - return (getEnvironmentVariable(`LANGSMITH_${name}`) || - getEnvironmentVariable(`LANGCHAIN_${name}`)); -} -function setEnvironmentVariable(name, value) { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - process.env[name] = value; - } -} -let cachedCommitSHAs; -/** - * Get the Git commit SHA from common environment variables - * used by different CI/CD platforms. - * @returns {string | undefined} The Git commit SHA or undefined if not found. - */ -function getShas() { - if (cachedCommitSHAs !== undefined) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT", - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = getEnvironmentVariable(env); - if (envVar !== undefined) { - shas[env] = envVar; + let datasetId_ = datasetId; + const datasetName_ = datasetName; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); } - } - cachedCommitSHAs = shas; - return shas; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js - -const isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; - } - const envVars = ["TRACING_V2", "TRACING"]; - return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js -const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js - - - - - - -function stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { - // Date only has millisecond precision, so we use the microseconds to break - // possible ties, avoiding incorrect run order - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); -} -/** - * Baggage header information - */ -class Baggage { - constructor(metadata, tags, project_name) { - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx], + }; }); - this.metadata = metadata; - this.tags = tags; - this.project_name = project_name; + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; } - static fromHeader(value) { - const items = value.split(","); - let metadata = {}; - let tags = []; - let project_name; - for (const item of items) { - const [key, uriValue] = item.split("="); - const value = decodeURIComponent(uriValue); - if (key === "langsmith-metadata") { - metadata = JSON.parse(value); - } - else if (key === "langsmith-tags") { - tags = value.split(","); - } - else if (key === "langsmith-project") { - project_name = value; + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); } + return message; + }); + const finalOutput = isLangChainMessage(generations) + ? convertLangChainMessageToExample(generations) + : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const rawExample = await this._get(path); + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type, + }; + return acc; + }, {}); } - return new Baggage(metadata, tags, project_name); + return example; } - toHeader() { - const items = []; - if (this.metadata && Object.keys(this.metadata).length > 0) { - items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { + let datasetId_; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - if (this.tags && this.tags.length > 0) { - items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); + else if (datasetId !== undefined) { + datasetId_ = datasetId; } - if (this.project_name) { - items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } - return items.join(","); - } -} -class run_trees_RunTree { - constructor(originalConfig) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "end_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "extra", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "serialized", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "reference_example_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "events", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "trace_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "dotted_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingEnabled", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Attachments associated with the run. - * Each entry is a tuple of [mime_type, bytes] - */ - Object.defineProperty(this, "attachments", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // If you pass in a run tree directly, return a shallow clone - if (run_trees_isRunTree(originalConfig)) { - Object.assign(this, { ...originalConfig }); - return; + else { + throw new Error("Must provide a datasetName or datasetId"); } - const defaultConfig = run_trees_RunTree.getDefaultConfig(); - const { metadata, ...config } = originalConfig; - const client = config.client ?? run_trees_RunTree.getSharedClient(); - const dedupedMetadata = { - ...metadata, - ...config?.extra?.metadata, - }; - config.extra = { ...config.extra, metadata: dedupedMetadata }; - Object.assign(this, { ...defaultConfig, ...config, client }); - if (!this.trace_id) { - if (this.parent_run) { - this.trace_id = this.parent_run.trace_id ?? this.id; + const params = new URLSearchParams({ dataset: datasetId_ }); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const inlineS3Urls_ = inlineS3Urls ?? true; + params.append("inline_s3_urls", inlineS3Urls_.toString()); + if (exampleIds !== undefined) { + for (const id_ of exampleIds) { + params.append("id", id_); } - else { - this.trace_id = this.id; + } + if (splits !== undefined) { + for (const split of splits) { + params.append("splits", split); } } - this.execution_order ??= 1; - this.child_execution_order ??= 1; - if (!this.dotted_order) { - const currentDottedOrder = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); - if (this.parent_run) { - this.dotted_order = - this.parent_run.dotted_order + "." + currentDottedOrder; + if (metadata !== undefined) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); + } + if (limit !== undefined) { + params.append("limit", limit.toString()); + } + if (offset !== undefined) { + params.append("offset", offset.toString()); + } + if (filter !== undefined) { + params.append("filter", filter); + } + if (includeAttachments === true) { + ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + } + let i = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || undefined, + }; + return acc; + }, {}); + } + yield example; + i++; } - else { - this.dotted_order = currentDottedOrder; + if (limit !== undefined && i >= limit) { + break; } } } - set metadata(metadata) { - this.extra = { - ...this.extra, - metadata: { - ...this.extra?.metadata, - ...metadata, - }, - }; - } - get metadata() { - return this.extra?.metadata; + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); } - static getDefaultConfig() { - return { - id: v4(), - run_type: "chain", - project_name: getLangSmithEnvironmentVariable("PROJECT") ?? - getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default", - child_runs: [], - api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time: Date.now(), - serialized: {}, - inputs: {}, - extra: {}, - }; + async updateExample(exampleIdOrUpdate, update) { + let exampleId; + if (update) { + exampleId = exampleIdOrUpdate; + } + else { + exampleId = exampleIdOrUpdate.id; + } + assertUuid(exampleId); + let updateToUse; + if (update) { + updateToUse = { id: exampleId, ...update }; + } + else { + updateToUse = exampleIdOrUpdate; + } + let datasetId; + if (updateToUse.dataset_id !== undefined) { + datasetId = updateToUse.dataset_id; + } + else { + const example = await this.readExample(exampleId); + datasetId = example.dataset_id; + } + return this._updateExamplesMultipart(datasetId, [updateToUse]); } - static getSharedClient() { - if (!run_trees_RunTree.sharedClient) { - run_trees_RunTree.sharedClient = new Client(); + async updateExamples(update) { + // We will naively get dataset id from first example and assume it works for all + let datasetId; + if (update[0].dataset_id === undefined) { + const example = await this.readExample(update[0].id); + datasetId = example.dataset_id; } - return run_trees_RunTree.sharedClient; + else { + datasetId = update[0].dataset_id; + } + return this._updateExamplesMultipart(datasetId, update); } - createChild(config) { - const child_execution_order = this.child_execution_order + 1; - const child = new run_trees_RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - client: this.client, - tracingEnabled: this.tracingEnabled, - execution_order: child_execution_order, - child_execution_order: child_execution_order, - }); - // Copy context vars over into the new run tree. - if (_LC_CONTEXT_VARIABLES_KEY in this) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - child[_LC_CONTEXT_VARIABLES_KEY] = - this[_LC_CONTEXT_VARIABLES_KEY]; + /** + * Get dataset version by closest date or exact tag. + * + * Use this to resolve the nearest version to a given timestamp or for a given tag. + * + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version + */ + async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { + let resolvedDatasetId; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + resolvedDatasetId = dataset.id; } - const LC_CHILD = Symbol.for("lc:child_config"); - const presentConfig = config.extra?.[LC_CHILD] ?? - this.extra[LC_CHILD]; - // tracing for LangChain is defined by the _parentRunId and runMap of the tracer - if (isRunnableConfigLike(presentConfig)) { - const newConfig = { ...presentConfig }; - const callbacks = isCallbackManagerLike(newConfig.callbacks) - ? newConfig.callbacks.copy?.() - : undefined; - if (callbacks) { - // update the parent run id - Object.assign(callbacks, { _parentRunId: child.id }); - // only populate if we're in a newer LC.JS version - callbacks.handlers - ?.find(isLangChainTracerLike) - ?.updateFromRunTree?.(child); - newConfig.callbacks = callbacks; - } - child.extra[LC_CHILD] = newConfig; + else { + resolvedDatasetId = datasetId; } - // propagate child_execution_order upwards - const visited = new Set(); - let current = this; - while (current != null && !visited.has(current.id)) { - visited.add(current.id); - current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); - current = current.parent_run; + assertUuid(resolvedDatasetId); + if ((asOf && tag) || (!asOf && !tag)) { + throw new Error("Exactly one of asOf and tag must be specified."); } - this.child_runs.push(child); - return child; + const params = new URLSearchParams(); + if (asOf !== undefined) { + params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + } + if (tag !== undefined) { + params.append("tag", tag); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this.headers }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "read dataset version"); + return await response.json(); } - async end(outputs, error, endTime = Date.now(), metadata) { - this.outputs = this.outputs ?? outputs; - this.error = this.error ?? error; - this.end_time = this.end_time ?? endTime; - if (metadata && Object.keys(metadata).length > 0) { - this.extra = this.extra - ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } - : { metadata }; + async listDatasetSplits({ datasetId, datasetName, asOf, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); } + const response = await this._get(`/datasets/${datasetId_}/splits`, params); + return response; } - _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - if (!runExtra.runtime) { - runExtra.runtime = {}; + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); } - if (runtimeEnv) { - for (const [k, v] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k]) { - runExtra.runtime[k] = v; - } - } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); - parent_run_id = undefined; + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; } else { - parent_run_id = run.parent_run?.id; - child_runs = []; + datasetId_ = datasetId; } - const persistedRun = { - id: run.id, - name: run.name, - start_time: run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs: child_runs, - parent_run_id: parent_run_id, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - tags: run.tags, - attachments: run.attachments, + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove, }; - return persistedRun; - } - async postRun(excludeChildRuns = true) { - try { - const runtimeEnv = getRuntimeEnvironment(); - const runCreate = await this._convertToCreate(this, runtimeEnv, true); - await this.client.createRun(runCreate); - if (!excludeChildRuns) { - warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); - } - } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update dataset splits", true); + } + /** + * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + */ + async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample, } = { loadChildRuns: false }) { + warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); + let run_; + if (typeof run === "string") { + run_ = await this.readRun(run, { loadChildRuns }); } - catch (error) { - console.error(`Error in postRun for run ${this.id}:`, error); + else if (typeof run === "object" && "id" in run) { + run_ = run; } - } - async patchRun() { - try { - const runUpdate = { - end_time: this.end_time, - error: this.error, - inputs: this.inputs, - outputs: this.outputs, - parent_run_id: this.parent_run?.id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, - dotted_order: this.dotted_order, - trace_id: this.trace_id, - tags: this.tags, - attachments: this.attachments, - session_name: this.project_name, - }; - await this.client.updateRun(this.id, runUpdate); + else { + throw new Error(`Invalid run type: ${typeof run}`); } - catch (error) { - console.error(`Error in patchRun for run ${this.id}`, error); + if (run_.reference_example_id !== null && + run_.reference_example_id !== undefined) { + referenceExample = await this.readExample(run_.reference_example_id); } + const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); + const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); + return feedbacks[0]; } - toJSON() { - return this._convertToCreate(this, undefined, false); - } - /** - * Add an event to the run tree. - * @param event - A single event or string to add - */ - addEvent(event) { - if (!this.events) { - this.events = []; + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { + if (!runId && !projectId) { + throw new Error("One of runId or projectId must be provided"); } - if (typeof event === "string") { - this.events.push({ - name: "event", - time: new Date().toISOString(), - message: event, - }); + if (runId && projectId) { + throw new Error("Only one of runId or projectId can be provided"); } - else { - this.events.push({ - ...event, - time: event.time ?? new Date().toISOString(), - }); + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {}, + }; + if (sourceRunId !== undefined && + feedback_source?.metadata !== undefined && + !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + if (feedback_source?.metadata !== undefined && + feedback_source.metadata["__run"]?.run_id !== undefined) { + assertUuid(feedback_source.metadata["__run"].run_id); } + const feedback = { + id: feedbackId ?? v4(), + run_id: runId, + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source: feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: projectId, + }; + const url = `${this.apiUrl}/feedback`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedback), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create feedback", true); + return feedback; } - static fromRunnableConfig(parentConfig, props) { - // We only handle the callback manager case for now - const callbackManager = parentConfig?.callbacks; - let parentRun; - let projectName; - let client; - let tracingEnabled = isTracingEnabled(); - if (callbackManager) { - const parentRunId = callbackManager?.getParentRunId?.() ?? ""; - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); - parentRun = langChainTracer?.getRun?.(parentRunId); - projectName = langChainTracer?.projectName; - client = langChainTracer?.client; - tracingEnabled = tracingEnabled || !!langChainTracer; + async updateFeedback(feedbackId, { score, value, correction, comment, }) { + const feedbackUpdate = {}; + if (score !== undefined && score !== null) { + feedbackUpdate["score"] = _formatFeedbackScore(score); } - if (!parentRun) { - return new run_trees_RunTree({ - ...props, - client, - tracingEnabled, - project_name: projectName, - }); + if (value !== undefined && value !== null) { + feedbackUpdate["value"] = value; } - const parentRunTree = new run_trees_RunTree({ - name: parentRun.name, - id: parentRun.id, - trace_id: parentRun.trace_id, - dotted_order: parentRun.dotted_order, - client, - tracingEnabled, - project_name: projectName, - tags: [ - ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), - ], - extra: { - metadata: { - ...parentRun?.extra?.metadata, - ...parentConfig?.metadata, - }, - }, + if (correction !== undefined && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== undefined && comment !== null) { + feedbackUpdate["comment"] = comment; + } + assertUuid(feedbackId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedbackUpdate), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - return parentRunTree.createChild(props); + await raiseForStatus(response, "update feedback", true); } - static fromDottedOrder(dottedOrder) { - return this.fromHeaders({ "langsmith-trace": dottedOrder }); + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; } - static fromHeaders(headers, inheritArgs) { - const rawHeaders = "get" in headers && typeof headers.get === "function" - ? { - "langsmith-trace": headers.get("langsmith-trace"), - baggage: headers.get("baggage"), - } - : headers; - const headerTrace = rawHeaders["langsmith-trace"]; - if (!headerTrace || typeof headerTrace !== "string") - return undefined; - const parentDottedOrder = headerTrace.trim(); - const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { - const [strTime, uuid] = part.split("Z"); - return { strTime, time: Date.parse(strTime + "Z"), uuid }; + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - const traceId = parsedDottedOrder[0].uuid; - const config = { - ...inheritArgs, - name: inheritArgs?.["name"] ?? "parent", - run_type: inheritArgs?.["run_type"] ?? "chain", - start_time: inheritArgs?.["start_time"] ?? Date.now(), - id: parsedDottedOrder.at(-1)?.uuid, - trace_id: traceId, - dotted_order: parentDottedOrder, - }; - if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { - const baggage = Baggage.fromHeader(rawHeaders["baggage"]); - config.metadata = baggage.metadata; - config.tags = baggage.tags; - config.project_name = baggage.project_name; + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + queryParams.append("run", runIds.join(",")); + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); + } + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); + } + } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; } - return new run_trees_RunTree(config); } - toHeaders(headers) { - const result = { - "langsmith-trace": this.dotted_order, - baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name).toHeader(), + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { + const body = { + run_id: runId, + feedback_key: feedbackKey, + feedback_config: feedbackConfig, }; - if (headers) { - for (const [key, value] of Object.entries(result)) { - headers.set(key, value); + if (expiration) { + if (typeof expiration === "string") { + body["expires_at"] = expiration; + } + else if (expiration?.hours || expiration?.minutes || expiration?.days) { + body["expires_in"] = expiration; } } + else { + body["expires_in"] = { + hours: 3, + }; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const result = await response.json(); return result; } -} -Object.defineProperty(run_trees_RunTree, "sharedClient", { - enumerable: true, - configurable: true, - writable: true, - value: null -}); -function run_trees_isRunTree(x) { - return (x !== undefined && - typeof x.createChild === "function" && - typeof x.postRun === "function"); -} -function isLangChainTracerLike(x) { - return (typeof x === "object" && - x != null && - typeof x.name === "string" && - x.name === "langchain_tracer"); -} -function containsLangChainTracerLike(x) { - return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); -} -function isCallbackManagerLike(x) { - return (typeof x === "object" && - x != null && - Array.isArray(x.handlers)); -} -function isRunnableConfigLike(x) { - // Check that it's an object with a callbacks arg - // that has either a CallbackManagerLike object with a langchain tracer within it - // or an array with a LangChainTracerLike object within it - return (x !== undefined && - typeof x.callbacks === "object" && - // Callback manager with a langchain tracer - (containsLangChainTracerLike(x.callbacks?.handlers) || - // Or it's an array with a LangChainTracerLike object within it - containsLangChainTracerLike(x.callbacks))); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js - -class MockAsyncLocalStorage { - getStore() { - return undefined; - } - run(_, callback) { - return callback(); - } -} -const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const mockAsyncLocalStorage = new MockAsyncLocalStorage(); -class AsyncLocalStorageProvider { - getInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; - } - initializeGlobalInstance(instance) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[TRACING_ALS_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[TRACING_ALS_KEY] = instance; + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { + if (experimentIds.length === 0) { + throw new Error("At least one experiment is required"); } - } -} -const AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); -function getCurrentRunTree(permitAbsentRunTree = false) { - const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); - if (!permitAbsentRunTree && !run_trees_isRunTree(runTree)) { - throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); - } - return runTree; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function withRunTree(runTree, fn) { - const storage = AsyncLocalStorageProviderSingleton.getInstance(); - return new Promise((resolve, reject) => { - storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); - }); -} -const ROOT = Symbol.for("langsmith:traceable:root"); -function isTraceableFunction(x -// eslint-disable-next-line @typescript-eslint/no-explicit-any -) { - return typeof x === "function" && "langsmith:traceable" in x; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2017-2022 Joachim Wester - * MIT licensed - */ -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function helpers_hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys = new Array(obj.length); - for (let k = 0; k < keys.length; k++) { - keys[k] = "" + k; + if (!referenceDatasetId) { + referenceDatasetId = (await this.readProject({ + projectId: experimentIds[0], + })).reference_dataset_id; } - return keys; - } - if (Object.keys) { - return Object.keys(obj); - } - let keys = []; - for (let i in obj) { - if (helpers_hasOwnProperty(obj, i)) { - keys.push(i); + if (!referenceDatasetId == null) { + throw new Error("A reference dataset is required"); } + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? new Date())?.toISOString(), + extra: {}, + }; + if (metadata) + body.extra["metadata"] = metadata; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + return await response.json(); } - return keys; -} -/** - * Deeply clone the object. - * https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) - * @param {any} obj value to clone - * @return {any} cloned obj - */ -function helpers_deepClone(obj) { - switch (typeof obj) { - case "object": - return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 - case "undefined": - return null; //this is how JSON.stringify behaves for array items - default: - return obj; //no need to clone primitives - } -} -//3x faster than cached /^\d+$/.test(str) -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { + assertUuid(runId); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) { + yield* tokens; } - return false; } - return true; -} -/** - * Escapes a json pointer path - * @param path The raw pointer - * @return the Escaped path - */ -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) - return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** - * Unescapes a json pointer path - * @param path The escaped pointer - * @return The unescaped path - */ -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -function _getPathRecursive(root, obj) { - let found; - for (let key in root) { - if (helpers_hasOwnProperty(root, key)) { - if (root[key] === obj) { - return escapePathComponent(key) + "/"; - } - else if (typeof root[key] === "object") { - found = _getPathRecursive(root[key], obj); - if (found != "") { - return escapePathComponent(key) + "/" + found; - } - } + _selectEvalResults(results) { + let results_; + if ("results" in results) { + results_ = results.results; } + else if (Array.isArray(results)) { + results_ = results; + } + else { + results_ = [results]; + } + return results_; } - return ""; -} -function getPath(root, obj) { - if (root === obj) { - return "/"; - } - const path = _getPathRecursive(root, obj); - if (path === "") { - throw new Error("Object not found in root"); - } - return `/${path}`; -} -/** - * Recursively checks whether an object has any undefined values inside. - */ -function hasUndefined(obj) { - if (obj === undefined) { - return true; - } - if (obj) { - if (Array.isArray(obj)) { - for (let i = 0, len = obj.length; i < len; i++) { - if (hasUndefined(obj[i])) { - return true; - } + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) { + sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; } - } - else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) { - if (hasUndefined(obj[objKeys[i]])) { - return true; - } + let runId_ = null; + if (res.targetRunId) { + runId_ = res.targetRunId; + } + else if (run) { + runId_ = run.id; } + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model", + })); } + return [evalResults, feedbacks]; } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" - ? JSON.stringify(args[key], null, 2) - : args[key]; // pretty print - if (typeof value !== "undefined") { - messageParts.push(`${key}: ${value}`); + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) { + queueIds.forEach((id, i) => { + assertUuid(id, `queueIds[${i}]`); + params.append("ids", id); + }); + } + if (name) + params.append("name", name); + if (nameContains) + params.append("name_contains", nameContains); + params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count++; + if (limit !== undefined && count >= limit) + break; } } - return messageParts.join("\n"); -} -class PatchError extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { name, index, operation, tree })); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: name + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions } = options; + const body = { + name, + description, + id: queueId || v4(), + rubric_instructions: rubricInstructions, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "index", { - enumerable: true, - configurable: true, - writable: true, - value: index + await raiseForStatus(response, "create annotation queue"); + const data = await response.json(); + return data; + } + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "operation", { - enumerable: true, - configurable: true, - writable: true, - value: operation + await raiseForStatus(response, "read annotation queue"); + const data = await response.json(); + return data; + } + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions } = options; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + name, + description, + rubric_instructions: rubricInstructions, + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.defineProperty(this, "tree", { - enumerable: true, - configurable: true, - writable: true, - value: tree + await raiseForStatus(response, "update annotation queue"); + } + /** + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete + */ + async deleteAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359 - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree, + await raiseForStatus(response, "delete annotation queue"); + } + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); + await raiseForStatus(response, "add runs to annotation queue"); } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js -// @ts-nocheck - -const JsonPatchError = PatchError; -const deepClone = helpers_deepClone; -/* We use a Javascript hash to store each - function. Each hash entry (property) uses - the operation identifiers specified in rfc6902. - In this way, we can map each patch operation - to its dedicated function in efficient way. - */ -/* The operations applicable to an object */ -const objOps = { - add: function (obj, key, document) { - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function (obj, key, document) { - var removed = obj[key]; - delete obj[key]; - return { newDocument: document, removed }; - }, - replace: function (obj, key, document) { - var removed = obj[key]; - obj[key] = this.value; - return { newDocument: document, removed }; - }, - move: function (obj, key, document) { - /* in case move target overwrites an existing value, - return the removed value, this can be taxing performance-wise, - and is potentially unneeded */ - let removed = getValueByPointer(document, this.path); - if (removed) { - removed = helpers_deepClone(removed); - } - const originalValue = applyOperation(document, { - op: "remove", - path: this.from, - }).removed; - applyOperation(document, { - op: "add", - path: this.path, - value: originalValue, + /** + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors + */ + async getRunFromAnnotationQueue(queueId, index) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - return { newDocument: document, removed }; - }, - copy: function (obj, key, document) { - const valueToCopy = getValueByPointer(document, this.from); - // enforce copy by value so further operations don't affect source (see issue #177) - applyOperation(document, { - op: "add", - path: this.path, - value: helpers_deepClone(valueToCopy), + await raiseForStatus(response, "get run from annotation queue"); + return await response.json(); + } + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, }); - return { newDocument: document }; - }, - test: function (obj, key, document) { - return { newDocument: document, test: _areEquals(obj[key], this.value) }; - }, - _get: function (obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - }, -}; -/* The operations applicable to an array. Many are the same as for the object */ -var arrOps = { - add: function (arr, i, document) { - if (isInteger(i)) { - arr.splice(i, 0, this.value); + await raiseForStatus(response, "delete run from annotation queue"); + } + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "get size from annotation queue"); + return await response.json(); + } + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return new Error(`Cannot ${action} for another tenant.\n + Current tenant: ${settings.tenant_handle}\n + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + const json = await res.json(); + if (!res.ok) { + const detail = typeof json.detail === "string" + ? json.detail + : JSON.stringify(json.detail); + const error = new Error(`Error ${res.status}: ${res.statusText}\n${detail}`); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + error.statusCode = res.status; + throw error; } - else { - // array props - arr[i] = this.value; + if (json.commits.length === 0) { + return undefined; } - // this may be needed when using '-' in an array - return { newDocument: document, index: i }; - }, - remove: function (arr, i, document) { - var removedList = arr.splice(i, 1); - return { newDocument: document, removed: removedList[0] }; - }, - replace: function (arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { newDocument: document, removed }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get, -}; -/** - * Retrieves a value from a JSON document by a JSON pointer. - * Returns the value. - * - * @param document The document to get the value from - * @param pointer an escaped JSON pointer - * @return The retrieved value - */ -function getValueByPointer(document, pointer) { - if (pointer == "") { - return document; + return json.commits[0].commit_hash; } - var getOriginalDestination = { op: "_get", path: pointer }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; -} -/** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the {newDocument, result} of the operation. - * It modifies the `document` and `operation` objects - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. - * - * @param document The document to patch - * @param operation The operation to apply - * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return `{newDocument, result}` after the operation - */ -function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) { - if (typeof validateOperation == "function") { - validateOperation(operation, 0, document, operation.path); + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + body: JSON.stringify({ like: like }), + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); + return await response.json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + if (commitHash !== "latest") { + return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; + } + else { + return `${this.getHostUrl()}/hub/${owner}/${promptName}`; + } } else { - validator(operation, 0); + const settings = await this._getSettings(); + if (commitHash !== "latest") { + return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + } + else { + return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + } } } - /* ROOT OPERATIONS */ - if (operation.path === "") { - let returnValue = { newDocument: document }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; + async promptExists(promptIdentifier) { + const prompt = await this.getPrompt(promptIdentifier); + return !!prompt; + } + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); + } + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + async *listCommits(promptOwnerAndName) { + for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { + yield* commits; } - else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document; //document we removed - return returnValue; + } + async *listPrompts(options) { + const params = new URLSearchParams(); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== undefined) { + params.append("is_public", options.isPublic.toString()); } - else if (operation.op === "move" || operation.op === "copy") { - // it's a move or copy to root - returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field - if (operation.op === "move") { - // report removed item - returnValue.removed = document; - } - return returnValue; + if (options?.query) { + params.append("query", options.query); } - else if (operation.op === "test") { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - returnValue.newDocument = document; - return returnValue; + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { + yield* prompts; } - else if (operation.op === "remove") { - // a remove on root - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; + } + async getPrompt(promptIdentifier) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + if (response.status === 404) { + return null; } - else if (operation.op === "_get") { - operation.value = document; - return returnValue; + await raiseForStatus(response, "get prompt"); + const result = await response.json(); + if (result.repo) { + return result.repo; } else { - /* bad operation */ - if (validateOperation) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else { - return returnValue; - } + return null; } - } /* END ROOT OPERATIONS */ - else { - if (!mutateDocument) { - document = helpers_deepClone(document); + } + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) { + throw new Error(`Cannot create a public prompt without first\n + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at:\n + https://smith.langchain.com/prompts`); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("create a prompt", owner); } - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document; - let t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift - let len = keys.length; - let existingPathFragment = undefined; - let key; - let validateFunction; - if (typeof validateOperation == "function") { - validateFunction = validateOperation; + const data = { + repo_handle: promptName, + ...(options?.description && { description: options.description }), + ...(options?.readme && { readme: options.readme }), + ...(options?.tags && { tags: options.tags }), + is_public: !!options?.isPublic, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create prompt"); + const { repo } = await response.json(); + return repo; + } + async createCommit(promptIdentifier, object, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } - else { - validateFunction = validator; + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash + ? await this._getLatestCommitHash(`${owner}/${promptName}`) + : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash, + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "create commit"); + const result = await response.json(); + return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); + } + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); + } + async _updateExamplesMultipart(datasetId, updates = []) { + if (!(await this._getMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); } - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) { - key = unescapePathComponent(key); + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + // Prepare the main example body + const exampleBody = { + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); } - if (banPrototypeModifications && - (key == "__proto__" || - (key == "prototype" && t > 0 && keys[t - 1] == "constructor"))) { - throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); } - if (validateOperation) { - if (existingPathFragment === undefined) { - if (obj[key] === undefined) { - existingPathFragment = keys.slice(0, t).join("/"); - } - else if (t == len - 1) { - existingPathFragment = operation.path; + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; } - if (existingPathFragment !== undefined) { - validateFunction(operation, 0, document, existingPathFragment); + else { + mimeType = attachment.mimeType; + data = attachment.data; } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); } } - t++; - if (Array.isArray(obj)) { - if (key === "-") { - key = obj.length; - } - else { - if (validateOperation && !isInteger(key)) { - throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); - } // only parse key when it's an integer for `arr.prop` to work - else if (isInteger(key)) { - key = ~~key; - } - } - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) { - throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); - } - const returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return returnValue; - } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { + type: "application/json", + }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); } - else { - if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch - if (returnValue.test === false) { - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + } + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { + method: "PATCH", + headers: this.headers, + body: formData, + }); + const result = await response.json(); + return result; + } + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); + } + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!(await this._getMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4()).toString(); + // Prepare the main example body + const exampleBody = { + created_at: example.created_at, + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + ...(example.source_run_id && { source_run_id: example.source_run_id }), + ...(example.use_source_run_io && { + use_source_run_io: example.use_source_run_io, + }), + ...(example.use_source_run_attachments && { + use_source_run_attachments: example.use_source_run_attachments, + }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; } - return returnValue; + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); } } - obj = obj[key]; - // If we have more keys in the path, but the next value isn't a non-null object, - // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again. - if (validateOperation && t < len && (!obj || typeof obj !== "object")) { - throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { + method: "POST", + headers: this.headers, + body: formData, + }); + await raiseForStatus(response, "upload examples"); + const result = await response.json(); + return result; } -} -/** - * Apply a full JSON Patch array on a JSON document. - * Returns the {newDocument, result} of the patch. - * It modifies the `document` object and `patch` - it gets the values by reference. - * If you would like to avoid touching your values, clone them: - * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. - * - * @param document The document to patch - * @param patch The patch to apply - * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. - * @param mutateDocument Whether to mutate the original document or clone it before applying - * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. - * @return An array of `{newDocument, result}` after the patch - */ -function core_applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + async updatePrompt(promptIdentifier, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); } + const [owner, promptName] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("update a prompt", owner); + } + const payload = {}; + if (options?.description !== undefined) + payload.description = options.description; + if (options?.readme !== undefined) + payload.readme = options.readme; + if (options?.tags !== undefined) + payload.tags = options.tags; + if (options?.isPublic !== undefined) + payload.is_public = options.isPublic; + if (options?.isArchived !== undefined) + payload.is_archived = options.isArchived; + // Check if payload is empty + if (Object.keys(payload).length === 0) { + throw new Error("No valid update options provided"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "PATCH", + body: JSON.stringify(payload), + headers: { + ...this.headers, + "Content-Type": "application/json", + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "update prompt"); + return response.json(); } - if (!mutateDocument) { - document = helpers_deepClone(document); - } - const results = new Array(patch.length); - for (let i = 0, length = patch.length; i < length; i++) { - // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true` - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; // in case root was replaced - } - results.newDocument = document; - return results; -} -/** - * Apply a single JSON Patch Operation on a JSON document. - * Returns the updated document. - * Suitable as a reducer. - * - * @param document The document to patch - * @param operation The operation to apply - * @return The updated document - */ -function applyReducer(document, operation, index) { - const operationResult = applyOperation(document, operation); - if (operationResult.test === false) { - // failed test - throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - } - return operationResult.newDocument; -} -/** - * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. - * @param {object} operation - operation object (patch) - * @param {number} index - index of operation in the sequence - * @param {object} [document] - object where the operation is supposed to be applied - * @param {string} [existingPathFragment] - comes along with `document` - */ -function validator(operation, index, document, existingPathFragment) { - if (typeof operation !== "object" || - operation === null || - Array.isArray(operation)) { - throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); - } - else if (!objOps[operation.op]) { - throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - } - else if (typeof operation.path !== "string") { - throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); - } - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { - // paths that aren't empty string should start with "/" - throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index, operation, document); - } - else if ((operation.op === "move" || operation.op === "copy") && - typeof operation.from !== "string") { - throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + async deletePrompt(promptIdentifier) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("delete a prompt", owner); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + return await response.json(); } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - operation.value === undefined) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + async pullPromptCommit(promptIdentifier, options) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, "pull prompt commit"); + const result = await response.json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples, + }; } - else if ((operation.op === "add" || - operation.op === "replace" || - operation.op === "test") && - hasUndefined(operation.value)) { - throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel, + }); + const prompt = JSON.stringify(promptObject.manifest); + return prompt; } - else if (document) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { - throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); + async pushPrompt(promptIdentifier, options) { + // Create or update prompt metadata + if (await this.promptExists(promptIdentifier)) { + if (options && Object.keys(options).some((key) => key !== "object")) { + await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); } } - else if (operation.op === "replace" || - operation.op === "remove" || - operation.op === "_get") { - if (operation.path !== existingPathFragment) { - throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } + else { + await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); } - else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: undefined, - }; - var error = core_validate([existingValue], document); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { - throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); - } + if (!options?.object) { + return await this._getPromptUrl(promptIdentifier); } + // Create a commit with the new manifest + const url = await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash, + }); + return url; } -} -/** - * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. - * If error is encountered, returns a JsonPatchError object - * @param sequence - * @param document - * @returns {JsonPatchError|undefined} - */ -function core_validate(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) { - throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + /** + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} + */ + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new Client({ + apiUrl: parsedApiUrl, + // Placeholder API key not needed anymore in most cases, but + // some private deployments may have API key-based rate limiting + // that would cause this to fail if we provide no value. + apiKey: "placeholder", + }); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; + } } - if (document) { - //clone document and sequence so that we can safely try applying operations - core_applyPatch(helpers_deepClone(document), helpers_deepClone(sequence), externalValidator || true); + catch (_) { + // `.hasDataset` will throw an error if the dataset does not exist. + // no-op in that case + } + // Fetch examples first, then create the dataset + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? undefined, + outputsSchema: ds.outputs_schema_definition ?? undefined, + }); + try { + await this.createExamples({ + inputs: examples.map((e) => e.inputs), + outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), + datasetId: dataset.id, + }); } - else { - externalValidator = externalValidator || validator; - for (var i = 0; i < sequence.length; i++) { - externalValidator(sequence[i], i, document, undefined); - } + catch (e) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + + "You should delete it manually."); + throw e; } } - catch (e) { - if (e instanceof JsonPatchError) { - return e; + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + // Try parsing as UUID + try { + assertUuid(urlOrToken); // Will throw if it's not a UUID. + return [apiUrl, urlOrToken]; } - else { - throw e; + catch (_) { + // no-op if it's not a uuid + } + // Parse as URL + try { + const parsedUrl = new URL(urlOrToken); + const pathParts = parsedUrl.pathname + .split("/") + .filter((part) => part !== ""); + if (pathParts.length >= numParts) { + const tokenUuid = pathParts[pathParts.length - numParts]; + return [apiUrl, tokenUuid]; + } + else { + throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + } + } + catch (error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); } } -} -// based on https://github.com/epoberezkin/fast-deep-equal -// MIT License -// Copyright (c) 2017 Evgeny Poberezkin -// 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. -function _areEquals(a, b) { - if (a === b) - return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) - return false; - for (i = length; i-- !== 0;) - if (!_areEquals(a[i], b[i])) - return false; - return true; + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + async awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); } - if (arrA != arrB) - return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length; i-- !== 0;) - if (!b.hasOwnProperty(keys[i])) - return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) - return false; + await Promise.all([ + ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), + this.batchIngestCaller.queue.onIdle(), + ]); + if (this.langSmithToOTELTranslator !== undefined) { + await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); } - return true; } - return a !== a && b !== b; +} +function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js -// @ts-nocheck -// Inlined because of ESM import issues -/*! - * https://github.com/Starcounter-Jack/JSON-Patch - * (c) 2013-2021 Joachim Wester - * MIT license - */ +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js + +const isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== undefined) { + return tracingEnabled; + } + const envVars = ["TRACING_V2", "TRACING"]; + return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); +}; +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js +const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); -var beforeDict = new WeakMap(); -class Mirror { - constructor(obj) { - Object.defineProperty(this, "obj", { +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js + + + + + + + + + +function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + // Date only has millisecond precision, so we use the microseconds to break + // possible ties, avoiding incorrect run order + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + const microsecondPrecisionDatestring = `${new Date(epoch) + .toISOString() + .slice(0, -1)}${paddedOrder}Z`; + return { + dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, + microsecondPrecisionDatestring, + }; +} +/** + * Baggage header information + */ +class Baggage { + constructor(metadata, tags, project_name, replicas) { + Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "observers", { + Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, - value: new Map() + value: void 0 }); - Object.defineProperty(this, "value", { + Object.defineProperty(this, "project_name", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.obj = obj; + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + this.replicas = replicas; + } + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + let replicas; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") { + metadata = JSON.parse(value); + } + else if (key === "langsmith-tags") { + tags = value.split(","); + } + else if (key === "langsmith-project") { + project_name = value; + } + else if (key === "langsmith-replicas") { + replicas = JSON.parse(value); + } + } + return new Baggage(metadata, tags, project_name, replicas); + } + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) { + items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); + } + if (this.tags && this.tags.length > 0) { + items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); + } + if (this.project_name) { + items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); + } + return items.join(","); } } -class ObserverInfo { - constructor(callback, observer) { - Object.defineProperty(this, "callback", { +class run_trees_RunTree { + constructor(originalConfig) { + Object.defineProperty(this, "id", { enumerable: true, configurable: true, writable: true, value: void 0 }); - Object.defineProperty(this, "observer", { + Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); - this.callback = callback; - this.observer = observer; - } -} -function getMirror(obj) { - return beforeDict.get(obj); -} -function getObserverFromMirror(mirror, callback) { - return mirror.observers.get(callback); -} -function removeObserverFromMirror(mirror, observer) { - mirror.observers.delete(observer.callback); -} -/** - * Detach an observer from an object - */ -function unobserve(root, observer) { - observer.unobserve(); -} -/** - * Observes changes made to an object, which can then be retrieved using generate - */ -function observe(obj, callback) { - var patches = []; - var observer; - var mirror = getMirror(obj); - if (!mirror) { - mirror = new Mirror(obj); - beforeDict.set(obj, mirror); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "trace_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "dotted_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Attachments associated with the run. + * Each entry is a tuple of [mime_type, bytes] + */ + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Projects to replicate this run to with optional updates. + */ + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_serialized_start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // If you pass in a run tree directly, return a shallow clone + if (run_trees_isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; + } + const defaultConfig = run_trees_RunTree.getDefaultConfig(); + const { metadata, ...config } = originalConfig; + const client = config.client ?? run_trees_RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config?.extra?.metadata, + }; + config.extra = { ...config.extra, metadata: dedupedMetadata }; + Object.assign(this, { ...defaultConfig, ...config, client }); + if (!this.trace_id) { + if (this.parent_run) { + this.trace_id = this.parent_run.trace_id ?? this.id; + } + else { + this.trace_id = this.id; + } + } + this.replicas = _ensureWriteReplicas(this.replicas); + this.execution_order ??= 1; + this.child_execution_order ??= 1; + if (!this.dotted_order) { + const { dottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) { + this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; + } + else { + this.dotted_order = dottedOrder; + } + this._serialized_start_time = microsecondPrecisionDatestring; + } } - else { - const observerInfo = getObserverFromMirror(mirror, callback); - observer = observerInfo && observerInfo.observer; + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata, + }, + }; } - if (observer) { - return observer; + get metadata() { + return this.extra?.metadata; } - observer = {}; - mirror.value = _deepClone(obj); - if (callback) { - observer.callback = callback; - observer.next = null; - var dirtyCheck = () => { - duplex_generate(observer); - }; - var fastCheck = () => { - clearTimeout(observer.next); - observer.next = setTimeout(dirtyCheck); + static getDefaultConfig() { + return { + id: v4(), + run_type: "chain", + project_name: getDefaultProjectName(), + child_runs: [], + api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time: Date.now(), + serialized: {}, + inputs: {}, + extra: {}, }; - if (typeof window !== "undefined") { - //not Node - window.addEventListener("mouseup", fastCheck); - window.addEventListener("keyup", fastCheck); - window.addEventListener("mousedown", fastCheck); - window.addEventListener("keydown", fastCheck); - window.addEventListener("change", fastCheck); + } + static getSharedClient() { + if (!run_trees_RunTree.sharedClient) { + run_trees_RunTree.sharedClient = new Client(); + } + return run_trees_RunTree.sharedClient; + } + createChild(config) { + const child_execution_order = this.child_execution_order + 1; + const child = new run_trees_RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + replicas: this.replicas, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order: child_execution_order, + }); + // Copy context vars over into the new run tree. + if (_LC_CONTEXT_VARIABLES_KEY in this) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + child[_LC_CONTEXT_VARIABLES_KEY] = + this[_LC_CONTEXT_VARIABLES_KEY]; + } + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config.extra?.[LC_CHILD] ?? + this.extra[LC_CHILD]; + // tracing for LangChain is defined by the _parentRunId and runMap of the tracer + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) + ? newConfig.callbacks.copy?.() + : undefined; + if (callbacks) { + // update the parent run id + Object.assign(callbacks, { _parentRunId: child.id }); + // only populate if we're in a newer LC.JS version + callbacks.handlers + ?.find(isLangChainTracerLike) + ?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; } - } - observer.patches = patches; - observer.object = obj; - observer.unobserve = () => { - duplex_generate(observer); - clearTimeout(observer.next); - removeObserverFromMirror(mirror, observer); - if (typeof window !== "undefined") { - window.removeEventListener("mouseup", fastCheck); - window.removeEventListener("keyup", fastCheck); - window.removeEventListener("mousedown", fastCheck); - window.removeEventListener("keydown", fastCheck); - window.removeEventListener("change", fastCheck); + // propagate child_execution_order upwards + const visited = new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; } - }; - mirror.observers.set(callback, new ObserverInfo(callback, observer)); - return observer; -} -/** - * Generate an array of patches from an observer - */ -function duplex_generate(observer, invertible = false) { - var mirror = beforeDict.get(observer.object); - _generate(mirror.value, observer.object, observer.patches, "", invertible); - if (observer.patches.length) { - applyPatch(mirror.value, observer.patches); + this.child_runs.push(child); + return child; } - var temp = observer.patches; - if (temp.length > 0) { - observer.patches = []; - if (observer.callback) { - observer.callback(temp); + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) { + this.extra = this.extra + ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } + : { metadata }; } } - return temp; -} -// Dirty check if obj is different from mirror, generate patches and update mirror -function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) { - return; + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + // Avoid overwriting the runtime environment if it's already set + if (runExtra?.runtime?.library === undefined) { + if (!runExtra.runtime) { + runExtra.runtime = {}; + } + if (runtimeEnv) { + for (const [k, v] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k]) { + runExtra.runtime[k] = v; + } + } + } + } + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + parent_run_id = undefined; + } + else { + parent_run_id = run.parent_run?.id ?? run.parent_run_id; + child_runs = []; + } + return { + id: run.id, + name: run.name, + start_time: run._serialized_start_time ?? run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs: child_runs, + parent_run_id: parent_run_id, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + tags: run.tags, + attachments: run.attachments, + events: run.events, + }; } - if (typeof obj.toJSON === "function") { - obj = obj.toJSON(); + _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) { + const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + if (projectName === this.project_name) { + return baseRun; + } + // Create a deterministic UUID mapping for this project + const createRemappedId = (originalId) => { + return v5(`${originalId}:${projectName}`, v5.DNS); + }; + // Remap the current run's ID + const newId = createRemappedId(baseRun.id); + const newTraceId = baseRun.trace_id + ? createRemappedId(baseRun.trace_id) + : undefined; + const newParentRunId = baseRun.parent_run_id + ? createRemappedId(baseRun.parent_run_id) + : undefined; + let newDottedOrder; + if (baseRun.dotted_order) { + const segments = _parseDottedOrder(baseRun.dotted_order); + const rebuilt = []; + // Process all segments except the last one + for (let i = 0; i < segments.length - 1; i++) { + const [timestamp, segmentId] = segments[i]; + const remappedId = createRemappedId(segmentId); + rebuilt.push(timestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + + remappedId); + } + // Process the last segment with the new run ID + const [lastTimestamp] = segments[segments.length - 1]; + rebuilt.push(lastTimestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + + newId); + newDottedOrder = rebuilt.join("."); + } + else { + newDottedOrder = undefined; + } + const remappedRun = { + ...baseRun, + id: newId, + trace_id: newTraceId, + parent_run_id: newParentRunId, + dotted_order: newDottedOrder, + session_name: projectName, + }; + return remappedRun; } - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var changed = false; - var deleted = false; - //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)" - for (var t = oldKeys.length - 1; t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (helpers_hasOwnProperty(obj, key) && - !(obj[key] === undefined && - oldVal !== undefined && - Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && - oldVal != null && - typeof newVal == "object" && - newVal != null && - Array.isArray(oldVal) === Array.isArray(newVal)) { - _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); + async postRun(excludeChildRuns = true) { + try { + const runtimeEnv = getRuntimeEnvironment(); + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl } of this.replicas) { + const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true); + await this.client.createRun(runCreate, { + apiKey, + apiUrl, + }); + } } else { - if (oldVal !== newVal) { - changed = true; - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(oldVal), - }); - } - patches.push({ - op: "replace", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(newVal), - }); + const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + await this.client.createRun(runCreate); + } + if (!excludeChildRuns) { + warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); } } } - else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) { - patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(oldVal), + catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); + } + } + async patchRun() { + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl, updates } of this.replicas) { + const runData = this._remapForProject(projectName ?? this.project_name); + await this.client.updateRun(runData.id, { + inputs: runData.inputs, + outputs: runData.outputs, + error: runData.error, + parent_run_id: runData.parent_run_id, + session_name: runData.session_name, + reference_example_id: runData.reference_example_id, + end_time: runData.end_time, + dotted_order: runData.dotted_order, + trace_id: runData.trace_id, + events: runData.events, + tags: runData.tags, + extra: runData.extra, + attachments: this.attachments, + ...updates, + }, { + apiKey, + apiUrl, }); } - patches.push({ - op: "remove", - path: path + "/" + escapePathComponent(key), - }); - deleted = true; // property has been deleted } else { - if (invertible) { - patches.push({ op: "test", path, value: mirror }); + try { + const runUpdate = { + end_time: this.end_time, + error: this.error, + inputs: this.inputs, + outputs: this.outputs, + parent_run_id: this.parent_run?.id ?? this.parent_run_id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + dotted_order: this.dotted_order, + trace_id: this.trace_id, + tags: this.tags, + attachments: this.attachments, + session_name: this.project_name, + }; + await this.client.updateRun(this.id, runUpdate); + } + catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); } - patches.push({ op: "replace", path, value: obj }); - changed = true; } } - if (!deleted && newKeys.length == oldKeys.length) { - return; + toJSON() { + return this._convertToCreate(this, undefined, false); } - for (var t = 0; t < newKeys.length; t++) { - var key = newKeys[t]; - if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== undefined) { - patches.push({ - op: "add", - path: path + "/" + escapePathComponent(key), - value: helpers_deepClone(obj[key]), + /** + * Add an event to the run tree. + * @param event - A single event or string to add + */ + addEvent(event) { + if (!this.events) { + this.events = []; + } + if (typeof event === "string") { + this.events.push({ + name: "event", + time: new Date().toISOString(), + message: event, + }); + } + else { + this.events.push({ + ...event, + time: event.time ?? new Date().toISOString(), + }); + } + } + static fromRunnableConfig(parentConfig, props) { + // We only handle the callback manager case for now + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client; + let tracingEnabled = isTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; + } + if (!parentRun) { + return new run_trees_RunTree({ + ...props, + client, + tracingEnabled, + project_name: projectName, }); } + const parentRunTree = new run_trees_RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client, + tracingEnabled, + project_name: projectName, + tags: [ + ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), + ], + extra: { + metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata, + }, + }, + }); + return parentRunTree.createChild(props); + } + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" + ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage"), + } + : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") + return undefined; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { strTime, time: Date.parse(strTime + "Z"), uuid }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder, + }; + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config.metadata = baggage.metadata; + config.tags = baggage.tags; + config.project_name = baggage.project_name; + config.replicas = baggage.replicas; + } + return new run_trees_RunTree(config); + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader(), + }; + if (headers) { + for (const [key, value] of Object.entries(result)) { + headers.set(key, value); + } + } + return result; } } -/** - * Create an array of patches from the differences in two objects - */ -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; +Object.defineProperty(run_trees_RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null +}); +function run_trees_isRunTree(x) { + return (x !== undefined && + typeof x.createChild === "function" && + typeof x.postRun === "function"); +} +function isLangChainTracerLike(x) { + return (typeof x === "object" && + x != null && + typeof x.name === "string" && + x.name === "langchain_tracer"); +} +function containsLangChainTracerLike(x) { + return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); +} +function isCallbackManagerLike(x) { + return (typeof x === "object" && + x != null && + Array.isArray(x.handlers)); +} +function isRunnableConfigLike(x) { + // Check that it's an object with a callbacks arg + // that has either a CallbackManagerLike object with a langchain tracer within it + // or an array with a LangChainTracerLike object within it + return (x !== undefined && + typeof x.callbacks === "object" && + // Callback manager with a langchain tracer + (containsLangChainTracerLike(x.callbacks?.handlers) || + // Or it's an array with a LangChainTracerLike object within it + containsLangChainTracerLike(x.callbacks))); +} +function _parseDottedOrder(dottedOrder) { + const parts = dottedOrder.split("."); + return parts.map((part) => { + const timestampStr = part.slice(0, -36); + const uuidStr = part.slice(-36); + // Parse timestamp: "%Y%m%dT%H%M%S%fZ" format + // Example: "20231215T143045123456Z" + const year = parseInt(timestampStr.slice(0, 4)); + const month = parseInt(timestampStr.slice(4, 6)) - 1; // JS months are 0-indexed + const day = parseInt(timestampStr.slice(6, 8)); + const hour = parseInt(timestampStr.slice(9, 11)); + const minute = parseInt(timestampStr.slice(11, 13)); + const second = parseInt(timestampStr.slice(13, 15)); + const microsecond = parseInt(timestampStr.slice(15, 21)); + const timestamp = new Date(year, month, day, hour, minute, second, microsecond / 1000); + return [timestamp, uuidStr]; + }); +} +function _getWriteReplicasFromEnv() { + const envVar = getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); + if (!envVar) + return []; + try { + const parsed = JSON.parse(envVar); + if (Array.isArray(parsed)) { + const replicas = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) { + console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected object, got ${typeof item}`); + continue; + } + if (typeof item.api_url !== "string") { + console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected string, got ${typeof item.api_url}`); + continue; + } + if (typeof item.api_key !== "string") { + console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected string, got ${typeof item.api_key}`); + continue; + } + replicas.push({ + apiUrl: item.api_url.replace(/\/$/, ""), + apiKey: item.api_key, + }); + } + return replicas; + } + else if (typeof parsed === "object" && parsed !== null) { + _checkEndpointEnvUnset(parsed); + const replicas = []; + for (const [url, key] of Object.entries(parsed)) { + const cleanUrl = url.replace(/\/$/, ""); + if (typeof key === "string") { + replicas.push({ + apiUrl: cleanUrl, + apiKey: key, + }); + } + else { + console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: ` + + `expected string, got ${typeof key}`); + continue; + } + } + return replicas; + } + else { + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + + `objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); + return []; + } + } + catch (e) { + if (isConflictingEndpointsError(e)) { + throw e; + } + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + + "objects with api_url and api_key properties, or object mapping url->apiKey"); + return []; + } +} +function _ensureWriteReplicas(replicas) { + // If null -> fetch from env + if (replicas) { + return replicas.map((replica) => { + if (Array.isArray(replica)) { + return { + projectName: replica[0], + updates: replica[1], + }; + } + return replica; + }); + } + return _getWriteReplicasFromEnv(); +} +function _checkEndpointEnvUnset(parsed) { + if (Object.keys(parsed).length > 0 && + getLangSmithEnvironmentVariable("ENDPOINT")) { + throw new ConflictingEndpointsError(); + } } -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js - - - -/** - * Default export for backwards compat - */ - - -/* harmony default export */ const fast_json_patch = ({ - ...src_core_namespaceObject, - // ...duplex, - JsonPatchError: PatchError, - deepClone: helpers_deepClone, - escapePathComponent: escapePathComponent, - unescapePathComponent: unescapePathComponent, -}); +;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; @@ -86062,7 +87427,13 @@ const env_getEnv = () => { return env; }; let env_runtimeEnvironment; +/** + * @deprecated Use getRuntimeEnvironmentSync instead + */ async function env_getRuntimeEnvironment() { + return getRuntimeEnvironmentSync(); +} +function getRuntimeEnvironmentSync() { if (env_runtimeEnvironment === undefined) { const env = env_getEnv(); env_runtimeEnvironment = { @@ -86250,35 +87621,84 @@ const isBaseCallbackHandler = (x) => { ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js + + +// TODO: Remove and just use base LangSmith Run type +const convertRunTreeToRun = (runTree) => { + if (!runTree) { + return undefined; + } + // Important that we return the raw run tree object since the reference + // is mutated in other places. + // TODO: Remove places where this is being done. + // eslint-disable-next-line no-param-reassign + runTree.events = runTree.events ?? []; + // eslint-disable-next-line no-param-reassign + runTree.child_runs = runTree.child_runs ?? []; + // TODO: Remove this cast and just use the LangSmith RunTree type. + return runTree; +}; +function convertRunToRunTree(run, parentRun) { + if (!run) { + return undefined; + } + return new run_trees_RunTree({ + ...run, + start_time: run._serialized_start_time ?? run.start_time, + parent_run: convertRunToRunTree(parentRun), + child_runs: run.child_runs + .map((r) => convertRunToRunTree(r)) + .filter((r) => r !== undefined), + extra: { + ...run.extra, + runtime: getRuntimeEnvironmentSync(), + }, + tracingEnabled: false, + }); +} // eslint-disable-next-line @typescript-eslint/no-explicit-any function _coerceToDict(value, defaultKey) { return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; } -function base_stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function base_convertToDottedOrderFormat(epoch, runId, executionOrder) { - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return (base_stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`) + runId); -} function isBaseTracer(x) { return typeof x._addRunToRunMap === "function"; } class BaseTracer extends BaseCallbackHandler { constructor(_fields) { super(...arguments); + /** @deprecated Use `runTreeMap` instead. */ Object.defineProperty(this, "runMap", { enumerable: true, configurable: true, writable: true, value: new Map() }); + Object.defineProperty(this, "runTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); } copy() { return this; } + getRunById(runId) { + if (runId === undefined) { + return undefined; + } + return this.usesRunTreeMap + ? convertRunTreeToRun(this.runTreeMap.get(runId)) + : this.runMap.get(runId); + } stringifyError(error) { // eslint-disable-next-line no-instanceof/no-instanceof if (error instanceof Error) { @@ -86293,10 +87713,10 @@ class BaseTracer extends BaseCallbackHandler { parentRun.child_runs.push(childRun); } _addRunToRunMap(run) { - const currentDottedOrder = base_convertToDottedOrderFormat(run.start_time, run.id, run.execution_order); + const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); const storedRun = { ...run }; + const parentRun = this.getRunById(storedRun.parent_run_id); if (storedRun.parent_run_id !== undefined) { - const parentRun = this.runMap.get(storedRun.parent_run_id); if (parentRun) { this._addChildRun(parentRun, storedRun); parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); @@ -86306,6 +87726,7 @@ class BaseTracer extends BaseCallbackHandler { parentRun.dotted_order, currentDottedOrder, ].join("."); + storedRun._serialized_start_time = microsecondPrecisionDatestring; } else { // This can happen naturally for callbacks added within a run @@ -86322,23 +87743,37 @@ class BaseTracer extends BaseCallbackHandler { else { storedRun.trace_id = storedRun.id; storedRun.dotted_order = currentDottedOrder; + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + if (this.usesRunTreeMap) { + const runTree = convertRunToRunTree(storedRun, parentRun); + if (runTree !== undefined) { + this.runTreeMap.set(storedRun.id, runTree); + } + } + else { + this.runMap.set(storedRun.id, storedRun); } - this.runMap.set(storedRun.id, storedRun); return storedRun; } async _endTrace(run) { - const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id); + const parentRun = run.parent_run_id !== undefined && this.getRunById(run.parent_run_id); if (parentRun) { parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); } else { await this.persistRun(run); } - this.runMap.delete(run.id); await this.onRunUpdate?.(run); + if (this.usesRunTreeMap) { + this.runTreeMap.delete(run.id); + } + else { + this.runMap.delete(run.id); + } } _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== undefined && this.runMap.get(parentRunId); + const parentRun = parentRunId !== undefined && this.getRunById(parentRunId); // If a run has no parent then execution order is 1 if (!parentRun) { return 1; @@ -86379,7 +87814,7 @@ class BaseTracer extends BaseCallbackHandler { return this._addRunToRunMap(run); } async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? + const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); await this.onRunCreate?.(run); await this.onLLMStart?.(run); @@ -86419,14 +87854,14 @@ class BaseTracer extends BaseCallbackHandler { return this._addRunToRunMap(run); } async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.runMap.get(runId) ?? + const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); await this.onRunCreate?.(run); await this.onLLMStart?.(run); return run; } async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "llm") { throw new Error("No LLM run to end."); } @@ -86442,7 +87877,7 @@ class BaseTracer extends BaseCallbackHandler { return run; } async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "llm") { throw new Error("No LLM run to end."); } @@ -86488,14 +87923,14 @@ class BaseTracer extends BaseCallbackHandler { return this._addRunToRunMap(run); } async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const run = this.runMap.get(runId) ?? + const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); await this.onRunCreate?.(run); await this.onChainStart?.(run); return run; } async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run) { throw new Error("No chain run to end."); } @@ -86513,7 +87948,7 @@ class BaseTracer extends BaseCallbackHandler { return run; } async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run) { throw new Error("No chain run to end."); } @@ -86561,7 +87996,7 @@ class BaseTracer extends BaseCallbackHandler { return this._addRunToRunMap(run); } async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? + const run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); await this.onRunCreate?.(run); await this.onToolStart?.(run); @@ -86569,7 +88004,7 @@ class BaseTracer extends BaseCallbackHandler { } // eslint-disable-next-line @typescript-eslint/no-explicit-any async handleToolEnd(output, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "tool") { throw new Error("No tool run to end"); } @@ -86584,7 +88019,7 @@ class BaseTracer extends BaseCallbackHandler { return run; } async handleToolError(error, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "tool") { throw new Error("No tool run to end"); } @@ -86599,7 +88034,7 @@ class BaseTracer extends BaseCallbackHandler { return run; } async handleAgentAction(action, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "chain") { return; } @@ -86614,7 +88049,7 @@ class BaseTracer extends BaseCallbackHandler { await this.onAgentAction?.(run); } async handleAgentEnd(action, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "chain") { return; } @@ -86656,14 +88091,14 @@ class BaseTracer extends BaseCallbackHandler { return this._addRunToRunMap(run); } async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const run = this.runMap.get(runId) ?? + const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); await this.onRunCreate?.(run); await this.onRetrieverStart?.(run); return run; } async handleRetrieverEnd(documents, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "retriever") { throw new Error("No retriever run to end"); } @@ -86678,7 +88113,7 @@ class BaseTracer extends BaseCallbackHandler { return run; } async handleRetrieverError(error, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "retriever") { throw new Error("No retriever run to end"); } @@ -86693,7 +88128,7 @@ class BaseTracer extends BaseCallbackHandler { return run; } async handleText(text, runId) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "chain") { return; } @@ -86705,7 +88140,7 @@ class BaseTracer extends BaseCallbackHandler { await this.onText?.(run); } async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.runMap.get(runId); + const run = this.getRunById(runId); if (!run || run?.run_type !== "llm") { throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); } @@ -86949,15 +88384,13 @@ class ConsoleCallbackHandler extends BaseTracer { } } -;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js - ;// CONCATENATED MODULE: ./node_modules/langsmith/index.js ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js let client; -const getDefaultLangChainClientSingleton = () => { +const tracer_getDefaultLangChainClientSingleton = () => { if (client === undefined) { const clientParams = env_getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { @@ -87006,52 +88439,39 @@ class tracer_langchain_LangChainTracer extends BaseTracer { writable: true, value: void 0 }); - const { exampleId, projectName, client } = fields; - this.projectName = - projectName ?? - env_getEnvironmentVariable("LANGCHAIN_PROJECT") ?? - env_getEnvironmentVariable("LANGCHAIN_SESSION"); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + const { exampleId, projectName, client, replicas } = fields; + this.projectName = projectName ?? getDefaultProjectName(); + this.replicas = replicas; this.exampleId = exampleId; - this.client = client ?? getDefaultLangChainClientSingleton(); + this.client = client ?? tracer_getDefaultLangChainClientSingleton(); const traceableTree = tracer_langchain_LangChainTracer.getTraceableRunTree(); if (traceableTree) { this.updateFromRunTree(traceableTree); } } - async _convertToCreate(run, example_id = undefined) { - return { - ...run, - extra: { - ...run.extra, - runtime: await env_getRuntimeEnvironment(), - }, - child_runs: undefined, - session_name: this.projectName, - reference_example_id: run.parent_run_id ? undefined : example_id, - }; - } async persistRun(_run) { } async onRunCreate(run) { - const persistedRun = await this._convertToCreate(run, this.exampleId); - await this.client.createRun(persistedRun); + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.postRun(); } async onRunUpdate(run) { - const runUpdate = { - end_time: run.end_time, - error: run.error, - outputs: run.outputs, - events: run.events, - inputs: run.inputs, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - parent_run_id: run.parent_run_id, - extra: run.extra, - session_name: this.projectName, - }; - await this.client.updateRun(run.id, runUpdate); + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.patchRun(); } getRun(id) { - return this.runMap.get(id); + return this.runTreeMap.get(id); } updateFromRunTree(runTree) { let rootRun = runTree; @@ -87071,56 +88491,28 @@ class tracer_langchain_LangChainTracer extends BaseTracer { if (!current || visited.has(current.id)) continue; visited.add(current.id); - // @ts-expect-error Types of property 'events' are incompatible. - this.runMap.set(current.id, current); + this.runTreeMap.set(current.id, current); if (current.child_runs) { queue.push(...current.child_runs); } } this.client = runTree.client ?? this.client; + this.replicas = runTree.replicas ?? this.replicas; this.projectName = runTree.project_name ?? this.projectName; this.exampleId = runTree.reference_example_id ?? this.exampleId; } - convertToRunTree(id) { - const runTreeMap = {}; - const runTreeList = []; - for (const [id, run] of this.runMap) { - // by converting the run map to a run tree, we are doing a copy - // thus, any mutation performed on the run tree will not be reflected - // back in the run map - // TODO: Stop using `this.runMap` in favour of LangSmith's `RunTree` - const runTree = new run_trees_RunTree({ - ...run, - child_runs: [], - parent_run: undefined, - // inherited properties - client: this.client, - project_name: this.projectName, - reference_example_id: this.exampleId, - tracingEnabled: true, - }); - runTreeMap[id] = runTree; - runTreeList.push([id, run.dotted_order]); - } - runTreeList.sort((a, b) => { - if (!a[1] || !b[1]) - return 0; - return a[1].localeCompare(b[1]); - }); - for (const [id] of runTreeList) { - const run = this.runMap.get(id); - const runTree = runTreeMap[id]; - if (!run || !runTree) - continue; - if (run.parent_run_id) { - const parentRunTree = runTreeMap[run.parent_run_id]; - if (parentRunTree) { - parentRunTree.child_runs.push(runTree); - runTree.parent_run = parentRunTree; - } - } - } - return runTreeMap[id]; + getRunTreeWithTracingConfig(id) { + const runTree = this.runTreeMap.get(id); + if (!runTree) + return undefined; + return new run_trees_RunTree({ + ...runTree, + client: this.client, + project_name: this.projectName, + replicas: this.replicas, + reference_example_id: this.exampleId, + tracingEnabled: true, + }); } static getTraceableRunTree() { try { @@ -87149,6 +88541,7 @@ const globals_getGlobalAsyncLocalStorageInstance = () => { /* eslint-disable @typescript-eslint/no-explicit-any */ + let queue; /** * Creates a queue using the p-queue library. The queue is configured to @@ -87202,8 +88595,12 @@ async function consumeCallback(promiseFn, wait) { * Waits for all promises in the queue to resolve. If the queue is * undefined, it immediately resolves a promise. */ -function awaitAllCallbacks() { - return typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(); +async function awaitAllCallbacks() { + const defaultClient = getDefaultLangChainClientSingleton(); + await Promise.allSettled([ + typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), + defaultClient.awaitPendingTraceBatches(), + ]); } ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js @@ -87783,7 +89180,7 @@ class CallbackManagerForToolRun extends BaseRunManager { * * // Example of using LLMChain with OpenAI and a simple prompt * const chain = new LLMChain({ - * llm: new ChatOpenAI({ temperature: 0.9 }), + * llm: new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0.9 }), * prompt, * }); * @@ -88324,7 +89721,7 @@ class async_local_storage_AsyncLocalStorageProvider { const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); let runTree; if (langChainTracer && parentRunId) { - runTree = langChainTracer.convertToRunTree(parentRunId); + runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); } else if (!avoidCreatingRootRunTree) { runTree = new run_trees_RunTree({ @@ -89894,14 +91291,14 @@ class EventStreamCallbackHandler extends BaseTracer { const async_caller_STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, + 400, // Bad Request + 401, // Unauthorized + 402, // Payment Required + 403, // Forbidden + 404, // Not Found + 405, // Method Not Allowed + 406, // Not Acceptable + 407, // Proxy Authentication Required 409, // Conflict ]; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -89971,7 +91368,7 @@ class async_caller_AsyncCaller { this.maxRetries = params.maxRetries ?? 6; this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + const PQueue = ( true ? p_queue_dist["default"] : p_queue_dist); this.queue = new PQueue({ concurrency: this.maxConcurrency }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -91116,7 +92513,7 @@ const _safeParse = (_Err) => (schema, value, _ctx) => { } : { success: true, data: result.value }; }; -const parse_safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); @@ -91129,7 +92526,7 @@ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { } : { success: true, data: result.value }; }; -const parse_safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); ;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/regexes.js const cuid = /^[cC][^\s-]{8,}$/; @@ -91799,14 +93196,14 @@ const versions_version = { -const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodType", (inst, def) => { +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { var _a; inst ?? (inst = {}); // avoids issues with using Math.random() in Next.js caching - util.defineLazy(inst._zod, "id", () => def.type + "_" + util.randomString(10)); + defineLazy(inst._zod, "id", () => def.type + "_" + randomString(10)); inst._zod.def = def; // set _def property inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = version; + inst._zod.version = versions_version; const checks = [...(inst._zod.def.checks ?? [])]; // if inst is itself a checks.$ZodCheck, run it as a check if (inst._zod.traits.has("$ZodCheck")) { @@ -91828,7 +93225,7 @@ const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (c } else { const runChecks = (payload, checks, ctx) => { - let isAborted = util.aborted(payload); + let isAborted = aborted(payload); let asyncResult; for (const ch of checks) { if (ch._zod.when) { @@ -91842,7 +93239,7 @@ const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (c const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && ctx?.async === false) { - throw new core.$ZodAsyncError(); + throw new $ZodAsyncError(); } if (asyncResult || _ instanceof Promise) { asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { @@ -91851,7 +93248,7 @@ const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (c if (nextLen === currLen) return; if (!isAborted) - isAborted = util.aborted(payload, currLen); + isAborted = aborted(payload, currLen); }); } else { @@ -91859,7 +93256,7 @@ const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (c if (nextLen === currLen) continue; if (!isAborted) - isAborted = util.aborted(payload, currLen); + isAborted = aborted(payload, currLen); } } if (asyncResult) { @@ -91873,7 +93270,7 @@ const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (c const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) - throw new core.$ZodAsyncError(); + throw new $ZodAsyncError(); return result.then((result) => runChecks(result, checks, ctx)); } return runChecks(result, checks, ctx); @@ -91892,7 +93289,7 @@ const $ZodType = /*@__PURE__*/ (/* unused pure expression or super */ null && (c vendor: "zod", version: 1, }; -}))); +}); const $ZodString = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); @@ -92334,7 +93731,7 @@ const schemas_$ZodUnknown = /*@__PURE__*/ (/* unused pure expression or super */ $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }))); -const $ZodNever = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNever", (inst, def) => { +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { payload.issues.push({ @@ -92345,7 +93742,7 @@ const $ZodNever = /*@__PURE__*/ (/* unused pure expression or super */ null && ( }); return payload; }; -}))); +}); const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { @@ -98204,7 +99601,7 @@ class $ZodRegistry { function registry() { return new $ZodRegistry(); } -const globalRegistry = /*@__PURE__*/ registry(); +const registries_globalRegistry = /*@__PURE__*/ registry(); ;// CONCATENATED MODULE: ./node_modules/zod/dist/esm/v4/core/api.js @@ -98602,7 +99999,7 @@ function api_unknown(Class) { function _never(Class, params) { return new Class({ type: "never", - ...util.normalizeParams(params), + ...normalizeParams(params), }); } function _void(Class, params) { @@ -99176,7 +100573,7 @@ function _function(params) { class JSONSchemaGenerator { constructor(params) { this.counter = 0; - this.metadataRegistry = params?.metadata ?? globalRegistry; + this.metadataRegistry = params?.metadata ?? registries_globalRegistry; this.target = params?.target ?? "draft-2020-12"; this.unrepresentable = params?.unrepresentable ?? "throw"; this.override = params?.override ?? (() => { }); @@ -100053,6 +101450,7 @@ const Options_defaultOptions = { emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" }; const getDefaultOptions = (options) => (typeof options === "string" ? { @@ -100073,6 +101471,7 @@ const getRefs = (options) => { : _options.basePath; return { ..._options, + flags: { hasReferencedOpenAiAnyType: false }, currentPath: currentPath, propertyPath: undefined, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ @@ -100087,9 +101486,33 @@ const getRefs = (options) => { }; }; +;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; + ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/any.js -function parseAnyDef() { - return {}; + +function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" + ? getRelativePath(anyDefinitionPath, refs.currentPath) + : anyDefinitionPath.join("/"), + }; } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/errorMessages.js @@ -100265,10 +101688,11 @@ function parseDefaultDef(_def, refs) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/effects.js + function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) - : {}; + : parseAnyDef(refs); } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/enum.js @@ -100716,6 +102140,7 @@ function stringifyRegExpWithFlags(regex, refs) { + function parseRecordDef(def, refs) { if (refs.target === "openAi") { console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); @@ -100730,7 +102155,7 @@ function parseRecordDef(def, refs) { [key]: parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "properties", key], - }) ?? {}, + }) ?? parseAnyDef(refs), }), {}), additionalProperties: refs.rejectedAdditionalProperties, }; @@ -100776,6 +102201,7 @@ function parseRecordDef(def, refs) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/map.js + function parseMapDef(def, refs) { if (refs.mapStrategy === "record") { return parseRecordDef(def, refs); @@ -100783,11 +102209,11 @@ function parseMapDef(def, refs) { const keys = parseDef(def.keyType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "0"], - }) || {}; + }) || parseAnyDef(refs); const values = parseDef(def.valueType._def, { ...refs, currentPath: [...refs.currentPath, "items", "items", "1"], - }) || {}; + }) || parseAnyDef(refs); return { type: "array", maxItems: 125, @@ -100819,10 +102245,16 @@ function parseNativeEnumDef(def) { } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/never.js -function parseNeverDef() { - return { - not: {}, - }; + +function parseNeverDef(refs) { + return refs.target === "openAi" + ? undefined + : { + not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"], + }), + }; } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/null.js @@ -101010,7 +102442,6 @@ function parseNumberDef(def, refs) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/object.js - function parseObjectDef(def, refs) { const forceOptionalIntoNullable = refs.target === "openAi"; const result = { @@ -101026,7 +102457,7 @@ function parseObjectDef(def, refs) { } let propOptional = safeIsOptional(propDef); if (propOptional && forceOptionalIntoNullable) { - if (propDef instanceof ZodOptional) { + if (propDef._def.typeName === "ZodOptional") { propDef = propDef._def.innerType; } if (!propDef.isNullable()) { @@ -101085,6 +102516,7 @@ function safeIsOptional(schema) { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/optional.js + const parseOptionalDef = (def, refs) => { if (refs.currentPath.toString() === refs.propertyPath?.toString()) { return parseDef(def.innerType._def, refs); @@ -101097,12 +102529,12 @@ const parseOptionalDef = (def, refs) => { ? { anyOf: [ { - not: {}, + not: parseAnyDef(refs), }, innerSchema, ], } - : {}; + : parseAnyDef(refs); }; ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js @@ -101190,15 +102622,17 @@ function parseTupleDef(def, refs) { } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js -function parseUndefinedDef() { + +function parseUndefinedDef(refs) { return { - not: {}, + not: parseAnyDef(refs), }; } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js -function parseUnknownDef() { - return {}; + +function parseUnknownDef(refs) { + return parseAnyDef(refs); } ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js @@ -101254,7 +102688,7 @@ const selectParser = (def, typeName, refs) => { case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); case ZodFirstPartyTypeKind.ZodUndefined: - return parseUndefinedDef(); + return parseUndefinedDef(refs); case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); case ZodFirstPartyTypeKind.ZodArray: @@ -101288,13 +102722,13 @@ const selectParser = (def, typeName, refs) => { return parsePromiseDef(def, refs); case ZodFirstPartyTypeKind.ZodNaN: case ZodFirstPartyTypeKind.ZodNever: - return parseNeverDef(); + return parseNeverDef(refs); case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); case ZodFirstPartyTypeKind.ZodAny: - return parseAnyDef(); + return parseAnyDef(refs); case ZodFirstPartyTypeKind.ZodUnknown: - return parseUnknownDef(); + return parseUnknownDef(refs); case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); case ZodFirstPartyTypeKind.ZodBranded: @@ -101318,6 +102752,8 @@ const selectParser = (def, typeName, refs) => { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/parseDef.js + + function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (refs.override) { @@ -101361,20 +102797,12 @@ const get$ref = (item, refs) => { if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return {}; + return parseAnyDef(refs); } - return refs.$refStrategy === "seen" ? {} : undefined; + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined; } } }; -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; const addMeta = (def, refs, jsonSchema) => { if (def.description) { jsonSchema.description = def.description; @@ -101388,15 +102816,16 @@ const addMeta = (def, refs, jsonSchema) => { ;// CONCATENATED MODULE: ./node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js + const zodToJsonSchema_zodToJsonSchema = (schema, options) => { const refs = getRefs(options); - const definitions = typeof options === "object" && options.definitions + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({ ...acc, [name]: parseDef(schema._def, { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name], - }, true) ?? {}, + }, true) ?? parseAnyDef(refs), }), {}) : undefined; const name = typeof options === "string" @@ -101409,7 +102838,7 @@ const zodToJsonSchema_zodToJsonSchema = (schema, options) => { : { ...refs, currentPath: [...refs.basePath, refs.definitionPath, name], - }, false) ?? {}; + }, false) ?? parseAnyDef(refs); const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" @@ -101418,6 +102847,26 @@ const zodToJsonSchema_zodToJsonSchema = (schema, options) => { if (title !== undefined) { main.title = title; } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" + ? "1" + : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName, + ].join("/"), + }, + }; + } + } const combined = name === undefined ? definitions ? { @@ -101490,6 +102939,7 @@ const zodToJsonSchema_zodToJsonSchema = (schema, options) => { + /* harmony default export */ const dist_esm = ((/* unused pure expression or super */ null && (zodToJsonSchema))); @@ -102814,7 +104264,7 @@ function interopParse(schema, input) { */ function getSchemaDescription(schema) { if (isZodSchemaV4(schema)) { - return globalRegistry.get(schema)?.description; + return registries_globalRegistry.get(schema)?.description; } if (isZodSchemaV3(schema)) { return schema.description; @@ -102915,6 +104365,55 @@ function isSimpleStringZodSchema(schema) { } return false; } +function isZodObjectV3(obj) { + // Zod v3 object schemas have _def.typeName === "ZodObject" + if (typeof obj === "object" && + obj !== null && + "_def" in obj && + typeof obj._def === "object" && + obj._def !== null && + "typeName" in obj._def && + obj._def.typeName === "ZodObject") { + return true; + } + return false; +} +function isZodObjectV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + // Zod v4 object schemas have _zod.def.type === "object" + if (typeof obj === "object" && + obj !== null && + "_zod" in obj && + typeof obj._zod === "object" && + obj._zod !== null && + "def" in obj._zod && + typeof obj._zod.def === "object" && + obj._zod.def !== null && + "type" in obj._zod.def && + obj._zod.def.type === "object") { + return true; + } + return false; +} +function isZodArrayV4(obj) { + if (!isZodSchemaV4(obj)) + return false; + // Zod v4 array schemas have _zod.def.type === "array" + if (typeof obj === "object" && + obj !== null && + "_zod" in obj && + typeof obj._zod === "object" && + obj._zod !== null && + "def" in obj._zod && + typeof obj._zod.def === "object" && + obj._zod.def !== null && + "type" in obj._zod.def && + obj._zod.def.type === "array") { + return true; + } + return false; +} /** * Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). * @@ -102922,33 +104421,10 @@ function isSimpleStringZodSchema(schema) { * @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. */ function isInteropZodObject(obj) { - if (isZodSchemaV3(obj)) { - // Zod v3 object schemas have _def.typeName === "ZodObject" - if (typeof obj === "object" && - obj !== null && - "_def" in obj && - typeof obj._def === "object" && - obj._def !== null && - "typeName" in obj._def && - obj._def.typeName === "ZodObject") { - return true; - } - } - if (isZodSchemaV4(obj)) { - // Zod v4 object schemas have _zod.def.type === "object" - if (typeof obj === "object" && - obj !== null && - "_zod" in obj && - typeof obj._zod === "object" && - obj._zod !== null && - "def" in obj._zod && - typeof obj._zod.def === "object" && - obj._zod.def !== null && - "type" in obj._zod.def && - obj._zod.def.type === "object") { - return true; - } - } + if (isZodObjectV3(obj)) + return true; + if (isZodObjectV4(obj)) + return true; return false; } /** @@ -103006,19 +104482,123 @@ function interopZodObjectPartial(schema) { } throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); } -function interopZodObjectPassthrough(schema) { - if (isInteropZodObject(schema)) { - if (isZodSchemaV3(schema)) { - return schema.passthrough(); - } - if (isZodSchemaV4(schema)) { - // Type reassign since ZodObjectV4 assumes that generics should be washed - const objectSchema = schema; - return clone(objectSchema, { - ...objectSchema._zod.def, - catchall: _unknown($ZodUnknown), - }); +/** + * Returns a strict version of a Zod object schema, disallowing unknown keys. + * Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness + * recursively to all nested object schemas and arrays of object schemas. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays. + * @returns {InteropZodObject} The strict Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function interopZodObjectStrict(schema, recursive = false) { + if (isZodSchemaV3(schema)) { + // TODO: v3 schemas aren't recursively handled here + // (currently not necessary since zodToJsonSchema handles this) + return schema.strict(); + } + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) { + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + // If the shape key is a v4 object schema, we need to make it strict + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectStrict(keySchema, recursive); + outputShape[key] = outputSchema; + } + // If the shape key is a v4 array schema, we need to make the element + // schema strict if it's an object schema + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) { + elementSchema = interopZodObjectStrict(elementSchema, recursive); + } + outputShape[key] = util_clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema, + }); + } + // Otherwise, just use the keySchema + else { + outputShape[key] = keySchema; + } + // Assign meta fields to the keySchema + const meta = registries_globalRegistry.get(keySchema); + if (meta) + registries_globalRegistry.add(outputShape[key], meta); + } } + const modifiedSchema = util_clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _never($ZodNever), + }); + const meta = registries_globalRegistry.get(schema); + if (meta) + registries_globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** + * Returns a passthrough version of a Zod object schema, allowing unknown keys. + * Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough + * recursively to all nested object schemas and arrays of object schemas. + * + * @template T - The type of the Zod object schema. + * @param {T} schema - The Zod object schema instance (either v3 or v4). + * @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays. + * @returns {InteropZodObject} The passthrough Zod object schema. + * @throws {Error} If the schema is not a Zod v3 or v4 object. + */ +function interopZodObjectPassthrough(schema, recursive = false) { + if (isZodObjectV3(schema)) { + // TODO: v3 schemas aren't recursively handled here + // (currently not necessary since zodToJsonSchema handles this) + return schema.passthrough(); + } + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) { + for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + // If the shape key is a v4 object schema, we need to make it passthrough + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectPassthrough(keySchema, recursive); + outputShape[key] = outputSchema; + } + // If the shape key is a v4 array schema, we need to make the element + // schema passthrough if it's an object schema + else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) { + elementSchema = interopZodObjectPassthrough(elementSchema, recursive); + } + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema, + }); + } + // Otherwise, just use the keySchema + else { + outputShape[key] = keySchema; + } + // Assign meta fields to the keySchema + const meta = globalRegistry.get(keySchema); + if (meta) + globalRegistry.add(outputShape[key], meta); + } + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _unknown($ZodUnknown), + }); + const meta = globalRegistry.get(schema); + if (meta) + globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; } throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); } @@ -103053,6 +104633,67 @@ function getInteropZodDefaultGetter(schema) { } return undefined; } +function isZodTransformV3(schema) { + return (isZodSchemaV3(schema) && + "typeName" in schema._def && + schema._def.typeName === "ZodEffects"); +} +function isZodTransformV4(schema) { + return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; +} +/** + * Returns the input type of a Zod transform schema, for both v3 and v4. + * If the schema is not a transform, returns undefined. If `recursive` is true, + * recursively processes nested object schemas and arrays of object schemas. + * + * @param schema - The Zod schema instance (v3 or v4) + * @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays. + * @returns The input Zod schema of the transform, or undefined if not a transform + */ +function interopZodTransformInputSchema(schema, recursive = false) { + // Zod v3: ._def.schema is the input schema for ZodEffects (transform) + if (isZodSchemaV3(schema)) { + if (isZodTransformV3(schema)) { + return interopZodTransformInputSchema(schema._def.schema, recursive); + } + // TODO: v3 schemas aren't recursively handled here + // (currently not necessary since zodToJsonSchema handles this) + return schema; + } + // Zod v4: _def.type is the input schema for ZodEffects (transform) + if (isZodSchemaV4(schema)) { + let outputSchema = schema; + if (isZodTransformV4(schema)) { + outputSchema = interopZodTransformInputSchema(schema._zod.def.in, recursive); + } + if (recursive) { + // Handle nested object schemas + if (isZodObjectV4(outputSchema)) { + const outputShape = outputSchema._zod.def.shape; + for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) { + outputShape[key] = interopZodTransformInputSchema(keySchema, recursive); + } + outputSchema = util_clone(outputSchema, { + ...outputSchema._zod.def, + shape: outputShape, + }); + } + // Handle nested array schemas + else if (isZodArrayV4(outputSchema)) { + const elementSchema = interopZodTransformInputSchema(outputSchema._zod.def.element, recursive); + outputSchema = util_clone(outputSchema, { + ...outputSchema._zod.def, + element: elementSchema, + }); + } + } + const meta = registries_globalRegistry.get(schema); + if (meta) + registries_globalRegistry.add(outputSchema, meta); + return outputSchema; + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_schema.js @@ -103067,7 +104708,14 @@ function getInteropZodDefaultGetter(schema) { */ function json_schema_toJsonSchema(schema) { if (isZodSchemaV4(schema)) { - return toJSONSchema(schema); + const inputSchema = interopZodTransformInputSchema(schema, true); + if (isZodObjectV4(inputSchema)) { + const strictSchema = interopZodObjectStrict(inputSchema, true); + return toJSONSchema(strictSchema); + } + else { + return toJSONSchema(schema); + } } if (isZodSchemaV3(schema)) { return zodToJsonSchema_zodToJsonSchema(schema); @@ -103982,8 +105630,9 @@ class Runnable extends Serializable { // add each chunk to the output stream const outerThis = this; async function consumeRunnableStream() { + let signal; + let listener = null; try { - let signal; if (options?.signal) { if ("any" in AbortSignal) { // Use native AbortSignal.any() if available (Node 19+) @@ -103997,9 +105646,10 @@ class Runnable extends Serializable { // Fallback for Node 18 and below - just use the provided signal signal = options.signal; // Ensure we still abort our controller when the parent signal aborts - options.signal.addEventListener("abort", () => { + listener = () => { abortController.abort(); - }, { once: true }); + }; + options.signal.addEventListener("abort", listener, { once: true }); } } else { @@ -104019,6 +105669,9 @@ class Runnable extends Serializable { } finally { await eventStreamer.finish(); + if (signal && listener) { + signal.removeEventListener("abort", listener); + } } } const runnableStreamConsumePromise = consumeRunnableStream(); @@ -104690,7 +106343,7 @@ class RunnableRetry extends RunnableBinding { * const promptTemplate = PromptTemplate.fromTemplate( * "Tell me a joke about {topic}", * ); - * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({})]); + * const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]); * const result = await chain.invoke({ topic: "bears" }); * ``` */ @@ -105330,9 +106983,9 @@ class base_RunnableLambda extends Runnable { * ); * * // Invoke the sequence with a single age input - * const res = sequence.invoke(25); + * const res = await sequence.invoke(25); * - * // { years_to_fifty: 25, years_to_hundred: 75 } + * // { years_to_fifty: 20, years_to_hundred: 70 } * ``` */ class RunnableParallel extends (/* unused pure expression or super */ null && (RunnableMap)) { @@ -105749,7 +107402,9 @@ class RunnablePick extends Runnable { const picked = this.keys .map((key) => [key, input[key]]) .filter((v) => v[1] !== undefined); - return picked.length === 0 ? undefined : Object.fromEntries(picked); + return picked.length === 0 + ? undefined + : Object.fromEntries(picked); } } async invoke(input, options) { @@ -106719,13 +108374,478 @@ Sha1.prototype.arrayBuffer = function () { dataView.setUint32(16, this.h4); return buffer; }; +let hasLoggedWarning = false; +/** + * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder. + * This function will be removed in a future version. + */ const insecureHash = (message) => { + if (!hasLoggedWarning) { + console.warn([ + `The default method for hashing keys is insecure and will be replaced in a future version,`, + `but hasn't been replaced yet as to not break existing caches. It's recommended that you use`, + `a more secure hashing algorithm to avoid cache poisoning.`, + ``, + `See this page for more information:`, + `|`, + `└> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm`, + ].join("\n")); + hasLoggedWarning = true; + } return new Sha1(true).update(message)["hex"](); }; +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha256/hash.js +// @ts-nocheck +// Inlined to deal with portability issues with importing crypto module +/** + * [js-sha256]{@link https://github.com/emn178/js-sha256} + * + * @version 0.11.1 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2025 + * @license MIT + */ +/*jslint bitwise: true */ + +var hash_HEX_CHARS = "0123456789abcdef".split(""); +var hash_EXTRA = [-2147483648, 8388608, 32768, 128]; +var hash_SHIFT = [24, 16, 8, 0]; +var K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, + 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; +var hash_OUTPUT_TYPES = (/* unused pure expression or super */ null && (["hex", "array", "digest", "arrayBuffer"])); +var hash_blocks = []; +function Sha256(is224, sharedMemory) { + if (sharedMemory) { + hash_blocks[0] = + hash_blocks[16] = + hash_blocks[1] = + hash_blocks[2] = + hash_blocks[3] = + hash_blocks[4] = + hash_blocks[5] = + hash_blocks[6] = + hash_blocks[7] = + hash_blocks[8] = + hash_blocks[9] = + hash_blocks[10] = + hash_blocks[11] = + hash_blocks[12] = + hash_blocks[13] = + hash_blocks[14] = + hash_blocks[15] = + 0; + this.blocks = hash_blocks; + } + else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + if (is224) { + this.h0 = 0xc1059ed8; + this.h1 = 0x367cd507; + this.h2 = 0x3070dd17; + this.h3 = 0xf70e5939; + this.h4 = 0xffc00b31; + this.h5 = 0x68581511; + this.h6 = 0x64f98fa7; + this.h7 = 0xbefa4fa4; + } + else { + // 256 + this.h0 = 0x6a09e667; + this.h1 = 0xbb67ae85; + this.h2 = 0x3c6ef372; + this.h3 = 0xa54ff53a; + this.h4 = 0x510e527f; + this.h5 = 0x9b05688c; + this.h6 = 0x1f83d9ab; + this.h7 = 0x5be0cd19; + } + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is224; +} +Sha256.prototype.update = function (message) { + if (this.finalized) { + return; + } + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) { + throw new Error(ERROR); + } + else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } + else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(ERROR); + } + } + } + else { + throw new Error(ERROR); + } + notString = true; + } + var code, index = 0, i, length = message.length, blocks = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = this.block; + this.block = + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + if (notString) { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >>> 2] |= message[index] << hash_SHIFT[i++ & 3]; + } + } + else { + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >>> 2] |= code << hash_SHIFT[i++ & 3]; + } + else if (code < 0x800) { + blocks[i >>> 2] |= (0xc0 | (code >>> 6)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << hash_SHIFT[i++ & 3]; + } + else if (code < 0xd800 || code >= 0xe000) { + blocks[i >>> 2] |= (0xe0 | (code >>> 12)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << hash_SHIFT[i++ & 3]; + } + else { + code = + 0x10000 + + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >>> 2] |= (0xf0 | (code >>> 18)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | ((code >>> 12) & 0x3f)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << hash_SHIFT[i++ & 3]; + blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << hash_SHIFT[i++ & 3]; + } + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } + else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += (this.bytes / 4294967296) << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha256.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex; + blocks[16] = this.block; + blocks[i >>> 2] |= hash_EXTRA[i & 3]; + this.block = blocks[16]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = this.block; + blocks[16] = + blocks[1] = + blocks[2] = + blocks[3] = + blocks[4] = + blocks[5] = + blocks[6] = + blocks[7] = + blocks[8] = + blocks[9] = + blocks[10] = + blocks[11] = + blocks[12] = + blocks[13] = + blocks[14] = + blocks[15] = + 0; + } + blocks[14] = (this.hBytes << 3) | (this.bytes >>> 29); + blocks[15] = this.bytes << 3; + this.hash(); +}; +Sha256.prototype.hash = function () { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16; j < 64; ++j) { + // rightrotate + t1 = blocks[j - 15]; + s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3); + t1 = blocks[j - 2]; + s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); + blocks[j] = (blocks[j - 16] + s0 + blocks[j - 7] + s1) << 0; + } + bc = b & c; + for (j = 0; j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks[0] - 1413257819; + h = (t1 - 150054599) << 0; + d = (t1 + 24177077) << 0; + } + else { + ab = 704751109; + t1 = blocks[0] - 210244248; + h = (t1 - 1521486534) << 0; + d = (t1 + 143694565) << 0; + } + this.first = false; + } + else { + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + ab = a & b; + maj = ab ^ (a & c) ^ bc; + ch = (e & f) ^ (~e & g); + t1 = h + s1 + ch + K[j] + blocks[j]; + t2 = s0 + maj; + h = (d + t1) << 0; + d = (t1 + t2) << 0; + } + s0 = + ((d >>> 2) | (d << 30)) ^ + ((d >>> 13) | (d << 19)) ^ + ((d >>> 22) | (d << 10)); + s1 = + ((h >>> 6) | (h << 26)) ^ + ((h >>> 11) | (h << 21)) ^ + ((h >>> 25) | (h << 7)); + da = d & a; + maj = da ^ (d & b) ^ ab; + ch = (g & h) ^ (~g & e); + t1 = f + s1 + ch + K[j + 1] + blocks[j + 1]; + t2 = s0 + maj; + g = (c + t1) << 0; + c = (t1 + t2) << 0; + s0 = + ((c >>> 2) | (c << 30)) ^ + ((c >>> 13) | (c << 19)) ^ + ((c >>> 22) | (c << 10)); + s1 = + ((g >>> 6) | (g << 26)) ^ + ((g >>> 11) | (g << 21)) ^ + ((g >>> 25) | (g << 7)); + cd = c & d; + maj = cd ^ (c & a) ^ da; + ch = (f & g) ^ (~f & h); + t1 = e + s1 + ch + K[j + 2] + blocks[j + 2]; + t2 = s0 + maj; + f = (b + t1) << 0; + b = (t1 + t2) << 0; + s0 = + ((b >>> 2) | (b << 30)) ^ + ((b >>> 13) | (b << 19)) ^ + ((b >>> 22) | (b << 10)); + s1 = + ((f >>> 6) | (f << 26)) ^ + ((f >>> 11) | (f << 21)) ^ + ((f >>> 25) | (f << 7)); + bc = b & c; + maj = bc ^ (b & d) ^ cd; + ch = (f & g) ^ (~f & h); + t1 = e + s1 + ch + K[j + 3] + blocks[j + 3]; + t2 = s0 + maj; + e = (a + t1) << 0; + a = (t1 + t2) << 0; + this.chromeBugWorkAround = true; + } + this.h0 = (this.h0 + a) << 0; + this.h1 = (this.h1 + b) << 0; + this.h2 = (this.h2 + c) << 0; + this.h3 = (this.h3 + d) << 0; + this.h4 = (this.h4 + e) << 0; + this.h5 = (this.h5 + f) << 0; + this.h6 = (this.h6 + g) << 0; + this.h7 = (this.h7 + h) << 0; +}; +Sha256.prototype.hex = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex = hash_HEX_CHARS[(h0 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h0 >>> 4) & 0x0f] + + hash_HEX_CHARS[h0 & 0x0f] + + hash_HEX_CHARS[(h1 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h1 >>> 4) & 0x0f] + + hash_HEX_CHARS[h1 & 0x0f] + + hash_HEX_CHARS[(h2 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h2 >>> 4) & 0x0f] + + hash_HEX_CHARS[h2 & 0x0f] + + hash_HEX_CHARS[(h3 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h3 >>> 4) & 0x0f] + + hash_HEX_CHARS[h3 & 0x0f] + + hash_HEX_CHARS[(h4 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h4 >>> 4) & 0x0f] + + hash_HEX_CHARS[h4 & 0x0f] + + hash_HEX_CHARS[(h5 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h5 >>> 4) & 0x0f] + + hash_HEX_CHARS[h5 & 0x0f] + + hash_HEX_CHARS[(h6 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h6 >>> 4) & 0x0f] + + hash_HEX_CHARS[h6 & 0x0f]; + if (!this.is224) { + hex += + hash_HEX_CHARS[(h7 >>> 28) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 24) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 20) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 16) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 12) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 8) & 0x0f] + + hash_HEX_CHARS[(h7 >>> 4) & 0x0f] + + hash_HEX_CHARS[h7 & 0x0f]; + } + return hex; +}; +Sha256.prototype.toString = Sha256.prototype.hex; +Sha256.prototype.digest = function () { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr = [ + (h0 >>> 24) & 0xff, + (h0 >>> 16) & 0xff, + (h0 >>> 8) & 0xff, + h0 & 0xff, + (h1 >>> 24) & 0xff, + (h1 >>> 16) & 0xff, + (h1 >>> 8) & 0xff, + h1 & 0xff, + (h2 >>> 24) & 0xff, + (h2 >>> 16) & 0xff, + (h2 >>> 8) & 0xff, + h2 & 0xff, + (h3 >>> 24) & 0xff, + (h3 >>> 16) & 0xff, + (h3 >>> 8) & 0xff, + h3 & 0xff, + (h4 >>> 24) & 0xff, + (h4 >>> 16) & 0xff, + (h4 >>> 8) & 0xff, + h4 & 0xff, + (h5 >>> 24) & 0xff, + (h5 >>> 16) & 0xff, + (h5 >>> 8) & 0xff, + h5 & 0xff, + (h6 >>> 24) & 0xff, + (h6 >>> 16) & 0xff, + (h6 >>> 8) & 0xff, + h6 & 0xff, + ]; + if (!this.is224) { + arr.push((h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, h7 & 0xff); + } + return arr; +}; +Sha256.prototype.array = Sha256.prototype.digest; +Sha256.prototype.arrayBuffer = function () { + this.finalize(); + var buffer = new ArrayBuffer(this.is224 ? 28 : 32); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) { + dataView.setUint32(28, this.h7); + } + return buffer; +}; +const sha256 = (...strings) => { + return new Sha256(false, true).update(strings.join("")).hex(); +}; + ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js + ;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/base.js @@ -106738,6 +108858,9 @@ const insecureHash = (message) => { * separate concerns and scale horizontally. * * TODO: Make cache key consistent across versions of LangChain. + * + * @deprecated Use `makeDefaultKeyEncoder()` to create a custom key encoder. + * This function will be removed in a future version. */ const getCacheKey = (...strings) => insecureHash(strings.join("_")); function deserializeStoredGeneration(storedGeneration) { @@ -106764,6 +108887,26 @@ function serializeGeneration(generation) { * Base class for all caches. All caches should extend this class. */ class BaseCache { + constructor() { + // For backwards compatibility, we use a default key encoder + // that uses SHA-1 to hash the prompt and LLM key. This will also print a warning + // about the security implications of using SHA-1 as a cache key. + Object.defineProperty(this, "keyEncoder", { + enumerable: true, + configurable: true, + writable: true, + value: getCacheKey + }); + } + /** + * Sets a custom key encoder function for the cache. + * This function should take a prompt and an LLM key and return a string + * that will be used as the cache key. + * @param keyEncoderFn The custom key encoder function. + */ + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } } const GLOBAL_MAP = new Map(); /** @@ -106788,7 +108931,7 @@ class InMemoryCache extends BaseCache { * @returns The data corresponding to the prompt and LLM key, or null if not found. */ lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(getCacheKey(prompt, llmKey)) ?? null); + return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); } /** * Updates the cache with new data using a prompt and an LLM key. @@ -106797,7 +108940,7 @@ class InMemoryCache extends BaseCache { * @param value The data to be stored. */ async update(prompt, llmKey, value) { - this.cache.set(getCacheKey(prompt, llmKey), value); + this.cache.set(this.keyEncoder(prompt, llmKey), value); } /** * Returns a global instance of InMemoryCache using a predefined global @@ -107420,13 +109563,37 @@ class BaseLanguageModel extends BaseLangChain { } this.caller = new async_caller_AsyncCaller(params ?? {}); } + /** + * Get the number of tokens in the content. + * @param content The content to get the number of tokens for. + * @returns The number of tokens in the content. + */ async getNumTokens(content) { - // TODO: Figure out correct value. - if (typeof content !== "string") { - return 0; + // Extract text content from MessageContent + let textContent; + if (typeof content === "string") { + textContent = content; + } + else { + /** + * Content is an array of MessageContentComplex + * + * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content. + * We need to find a better way to do this. + * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116 + */ + textContent = content + .map((item) => { + if (typeof item === "string") + return item; + if (item.type === "text" && "text" in item) + return item.text; + return ""; + }) + .join(""); } // fallback to approximate calculation if tiktoken is not available - let numTokens = Math.ceil(content.length / 4); + let numTokens = Math.ceil(textContent.length / 4); if (!this._encoding) { try { this._encoding = await tiktoken_encodingForModel("modelName" in this @@ -107439,7 +109606,7 @@ class BaseLanguageModel extends BaseLangChain { } if (this._encoding) { try { - numTokens = this._encoding.encode(content).length; + numTokens = this._encoding.encode(textContent).length; } catch (error) { console.warn("Failed to calculate number of tokens, falling back to approximate count", error); @@ -107619,7 +109786,7 @@ class RunnablePassthrough extends Runnable { * schema: async () => db.getTableInfo(), * }), * prompt, - * new ChatOpenAI({}).withConfig({ stop: ["\nSQLResult:"] }), + * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), * new StringOutputParser(), * ]); * const result = await sqlQueryGeneratorChain.invoke({ @@ -109350,7 +111517,7 @@ class MarkdownListOutputParser extends ListOutputParser { * * const chain = RunnableSequence.from([ * promptTemplate, - * new ChatOpenAI({}), + * new ChatOpenAI({ model: "gpt-4o-mini" }), * new StringOutputParser(), * ]); * @@ -109949,41 +112116,41 @@ const initializeSax = function () { } var S = 0; sax.STATE = { - BEGIN: S++, - BEGIN_WHITESPACE: S++, - TEXT: S++, - TEXT_ENTITY: S++, - OPEN_WAKA: S++, - SGML_DECL: S++, - SGML_DECL_QUOTED: S++, - DOCTYPE: S++, - DOCTYPE_QUOTED: S++, - DOCTYPE_DTD: S++, - DOCTYPE_DTD_QUOTED: S++, - COMMENT_STARTING: S++, - COMMENT: S++, - COMMENT_ENDING: S++, - COMMENT_ENDED: S++, - CDATA: S++, - CDATA_ENDING: S++, - CDATA_ENDING_2: S++, - PROC_INST: S++, - PROC_INST_BODY: S++, - PROC_INST_ENDING: S++, - OPEN_TAG: S++, - OPEN_TAG_SLASH: S++, - ATTRIB: S++, - ATTRIB_NAME: S++, - ATTRIB_NAME_SAW_WHITE: S++, - ATTRIB_VALUE: S++, - ATTRIB_VALUE_QUOTED: S++, - ATTRIB_VALUE_CLOSED: S++, - ATTRIB_VALUE_UNQUOTED: S++, - ATTRIB_VALUE_ENTITY_Q: S++, - ATTRIB_VALUE_ENTITY_U: S++, - CLOSE_TAG: S++, - CLOSE_TAG_SAW_WHITE: S++, - SCRIPT: S++, + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //