reconstruct and build @anthropic-ai/claude-code source from source map

- Extract 4756 source files from cli.js.map (57MB)
- Set up Bun build system with bun:bundle feature flag shim
- Configure 90+ compile-time feature flags matching production defaults
- Inject MACRO constants (VERSION, BUILD_TIME, etc.)
- Create stubs for private packages (color-diff-napi, modifiers-napi, etc.)
- Install all public dependencies via pnpm
- Patch commander v14 to allow multi-char short flags (-d2e)
- Build output: dist/cli.js (22MB), verified working
This commit is contained in:
janlaywss
2026-03-31 19:19:50 +08:00
commit 6187147b74
37865 changed files with 5438634 additions and 0 deletions

21
claude-code-source/node_modules/.bin/anthropic-ai-sdk generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/@anthropic-ai+sdk@0.80.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/@anthropic-ai+sdk@0.80.0_zod@4.3.6/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/@anthropic-ai+sdk@0.80.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/@anthropic-ai+sdk@0.80.0_zod@4.3.6/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/@anthropic-ai+sdk@0.80.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/bin/cli" "$@"
else
exec node "$basedir/../.pnpm/@anthropic-ai+sdk@0.80.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/bin/cli" "$@"
fi

21
claude-code-source/node_modules/.bin/marked generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/marked@17.0.5/node_modules/marked/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/marked@17.0.5/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/marked@17.0.5/node_modules/marked/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/marked@17.0.5/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/marked@17.0.5/node_modules/marked/bin/marked.js" "$@"
else
exec node "$basedir/../.pnpm/marked@17.0.5/node_modules/marked/bin/marked.js" "$@"
fi

21
claude-code-source/node_modules/.bin/qrcode generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/qrcode@1.5.4/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/qrcode@1.5.4/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/qrcode@1.5.4/node_modules/qrcode/bin/qrcode" "$@"
else
exec node "$basedir/../.pnpm/qrcode@1.5.4/node_modules/qrcode/bin/qrcode" "$@"
fi

21
claude-code-source/node_modules/.bin/semver generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/semver@7.7.4/node_modules/semver/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/semver@7.7.4/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/semver@7.7.4/node_modules/semver/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/semver@7.7.4/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/semver@7.7.4/node_modules/semver/bin/semver.js" "$@"
else
exec node "$basedir/../.pnpm/semver@7.7.4/node_modules/semver/bin/semver.js" "$@"
fi

21
claude-code-source/node_modules/.bin/tree-kill generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/tree-kill@1.2.2/node_modules/tree-kill/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/tree-kill@1.2.2/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/tree-kill@1.2.2/node_modules/tree-kill/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/tree-kill@1.2.2/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/tree-kill@1.2.2/node_modules/tree-kill/cli.js" "$@"
else
exec node "$basedir/../.pnpm/tree-kill@1.2.2/node_modules/tree-kill/cli.js" "$@"
fi

21
claude-code-source/node_modules/.bin/tsc generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules/typescript/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules/typescript/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/typescript@6.0.2/node_modules/typescript/bin/tsc" "$@"
else
exec node "$basedir/../.pnpm/typescript@6.0.2/node_modules/typescript/bin/tsc" "$@"
fi

21
claude-code-source/node_modules/.bin/tsserver generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules/typescript/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules/typescript/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/typescript@6.0.2/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/typescript@6.0.2/node_modules/typescript/bin/tsserver" "$@"
else
exec node "$basedir/../.pnpm/typescript@6.0.2/node_modules/typescript/bin/tsserver" "$@"
fi

21
claude-code-source/node_modules/.bin/xss generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/xss@1.0.15/node_modules/xss/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/xss@1.0.15/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/xss@1.0.15/node_modules/xss/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/xss@1.0.15/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/xss@1.0.15/node_modules/xss/bin/xss" "$@"
else
exec node "$basedir/../.pnpm/xss@1.0.15/node_modules/xss/bin/xss" "$@"
fi

21
claude-code-source/node_modules/.bin/yaml generated vendored Executable file
View File

@@ -0,0 +1,21 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -z "$NODE_PATH" ]; then
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/yaml@2.8.3/node_modules/yaml/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/yaml@2.8.3/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules"
else
export NODE_PATH="/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/yaml@2.8.3/node_modules/yaml/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/yaml@2.8.3/node_modules:/Users/bytedance/claude-code/claude-code-source/node_modules/.pnpm/node_modules:$NODE_PATH"
fi
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../.pnpm/yaml@2.8.3/node_modules/yaml/bin.mjs" "$@"
else
exec node "$basedir/../.pnpm/yaml@2.8.3/node_modules/yaml/bin.mjs" "$@"
fi

View File

@@ -0,0 +1,50 @@
import ansiStyles from "ansi-styles";
export const ESCAPES = new Set([27, 155]); // \x1b and \x9b
export const CSI = "[".codePointAt(0);
export const OSC = "]".codePointAt(0);
export const endCodesSet = new Set();
const endCodesMap = new Map();
for (const [start, end] of ansiStyles.codes) {
endCodesSet.add(ansiStyles.color.ansi(end));
endCodesMap.set(ansiStyles.color.ansi(start), ansiStyles.color.ansi(end));
}
export const linkStartCodePrefix = "\x1B]8;;";
export const linkStartCodePrefixCharCodes = linkStartCodePrefix
.split("")
.map((char) => char.charCodeAt(0));
export const linkCodeSuffix = "\x07";
export const linkCodeSuffixCharCode = linkCodeSuffix.charCodeAt(0);
export const linkEndCode = `\x1B]8;;${linkCodeSuffix}`;
export function getLinkStartCode(url) {
return `${linkStartCodePrefix}${url}${linkCodeSuffix}`;
}
export function getEndCode(code) {
if (endCodesSet.has(code))
return code;
if (endCodesMap.has(code))
return endCodesMap.get(code);
// We have a few special cases to handle here:
// Links:
if (code.startsWith(linkStartCodePrefix))
return linkEndCode;
code = code.slice(2);
// 8-bit/24-bit colors:
if (code.startsWith("38")) {
return ansiStyles.color.close;
}
else if (code.startsWith("48")) {
return ansiStyles.bgColor.close;
}
// Otherwise find the reset code in the ansi-styles map
const ret = ansiStyles.codes.get(parseInt(code, 10));
if (ret) {
return ansiStyles.color.ansi(ret);
}
else {
return ansiStyles.reset.open;
}
}
export function ansiCodesToString(codes) {
return codes.map((code) => code.code).join("");
}
//# sourceMappingURL=ansiCodes.js.map

View File

@@ -0,0 +1,17 @@
import { undoAnsiCodes } from "./undo.js";
/**
* Returns the minimum amount of ANSI codes necessary to get from the compound style `from` to `to`.
* Both `from` and `to` are expected to be reduced.
*/
export function diffAnsiCodes(from, to) {
const endCodesInTo = new Set(to.map((code) => code.endCode));
const startCodesInFrom = new Set(from.map((code) => code.code));
return [
// Ignore all styles in `from` that are not overwritten or removed by `to`
// Disable all styles in `from` that are removed in `to`
...undoAnsiCodes(from.filter((code) => !endCodesInTo.has(code.endCode))),
// Add all styles in `to` that don't exist in `from`
...to.filter((code) => !startCodesInFrom.has(code.code)),
];
}
//# sourceMappingURL=diff.js.map

View File

@@ -0,0 +1,7 @@
export { ansiCodesToString } from "./ansiCodes.js";
export { diffAnsiCodes } from "./diff.js";
export { reduceAnsiCodes, reduceAnsiCodesIncremental } from "./reduce.js";
export * from "./styledChars.js";
export * from "./tokenize.js";
export { undoAnsiCodes } from "./undo.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,38 @@
import ansiStyles from "ansi-styles";
import { endCodesSet } from "./ansiCodes.js";
/** Reduces the given array of ANSI codes to the minimum necessary to render with the same style */
export function reduceAnsiCodes(codes) {
return reduceAnsiCodesIncremental([], codes);
}
/** Like {@link reduceAnsiCodes}, but assumes that `codes` is already reduced. Further reductions are only done for the items in `newCodes`. */
export function reduceAnsiCodesIncremental(codes, newCodes) {
let ret = [...codes];
for (const code of newCodes) {
if (code.code === ansiStyles.reset.open) {
// Reset code, disable all codes
ret = [];
}
else if (endCodesSet.has(code.code)) {
// This is an end code, disable all matching start codes
ret = ret.filter((retCode) => retCode.endCode !== code.code);
}
else {
// This is a start code. Remove codes it "overrides", then add it.
// If a new code has the same endCode, it "overrides" existing ones.
// Special case: Intensity codes (1m, 2m) can coexist (both end with 22m).
const isIntensityCode = code.code === ansiStyles.bold.open || code.code === ansiStyles.dim.open;
// Add intensity codes only if not already present
if (isIntensityCode) {
if (!ret.find((retCode) => retCode.code === code.code && retCode.endCode === code.endCode)) {
ret.push(code);
}
}
else {
ret = ret.filter((retCode) => retCode.endCode !== code.endCode);
ret.push(code);
}
}
}
return ret;
}
//# sourceMappingURL=reduce.js.map

View File

@@ -0,0 +1,38 @@
import { ansiCodesToString } from "./ansiCodes.js";
import { diffAnsiCodes } from "./diff.js";
import { reduceAnsiCodesIncremental } from "./reduce.js";
export function styledCharsFromTokens(tokens) {
let codes = [];
const ret = [];
for (const token of tokens) {
if (token.type === "ansi") {
codes = reduceAnsiCodesIncremental(codes, [token]);
}
else if (token.type === "char") {
ret.push({
...token,
styles: [...codes],
});
}
}
return ret;
}
export function styledCharsToString(chars) {
let ret = "";
for (let i = 0; i < chars.length; i++) {
const char = chars[i];
if (i === 0) {
ret += ansiCodesToString(char.styles);
}
else {
ret += ansiCodesToString(diffAnsiCodes(chars[i - 1].styles, char.styles));
}
ret += char.value;
// reset active styles at the end of the string
if (i === chars.length - 1) {
ret += ansiCodesToString(diffAnsiCodes(char.styles, []));
}
}
return ret;
}
//# sourceMappingURL=styledChars.js.map

View File

@@ -0,0 +1,141 @@
import isFullwidthCodePoint from "is-fullwidth-code-point";
import { CSI, ESCAPES, getEndCode, linkStartCodePrefix, linkStartCodePrefixCharCodes, OSC, } from "./ansiCodes.js";
// HOT PATH: Use only basic string/char code operations for maximum performance
function parseLinkCode(string, offset) {
string = string.slice(offset);
for (let index = 1; index < linkStartCodePrefixCharCodes.length; index++) {
if (string.charCodeAt(index) !== linkStartCodePrefixCharCodes[index]) {
return undefined;
}
}
// This is a link code (with or without the URL part). Find the end of it.
const endIndex = string.indexOf("\x07", linkStartCodePrefix.length);
if (endIndex === -1)
return undefined;
return string.slice(0, endIndex + 1);
}
const CC_0 = "0".charCodeAt(0);
const CC_9 = "9".charCodeAt(0);
const CC_SEMI = ";".charCodeAt(0);
const CC_M = "m".charCodeAt(0);
/**
* Scans through the given string and finds the index of the last character of an SGR sequence
* like `\x1B[38;2;123;123;123m`. This assumes that the string has been checked to start with `\x1B[`.
* Returns -1 if no valid SGR sequence is found.
*/
function findSGRSequenceEndIndex(str) {
for (let index = 2; index < str.length; index++) {
const charCode = str.charCodeAt(index);
// m marks the end of the SGR sequence
if (charCode === CC_M)
return index;
// Digits and semicolons are valid
if (charCode === CC_SEMI)
continue;
if (charCode >= CC_0 && charCode <= CC_9)
continue;
// Everything else is invalid
break;
}
return -1;
}
// HOT PATH: Use only basic string/char code operations for maximum performance
function parseSGRSequence(string, offset) {
string = string.slice(offset);
const endIndex = findSGRSequenceEndIndex(string);
if (endIndex === -1)
return;
return string.slice(0, endIndex + 1);
}
/**
* Splits compound SGR sequences like `\x1B[1;3;31m` into individual components
*/
function splitCompoundSGRSequences(code) {
if (!code.includes(";")) {
// Not a compound code
return [code];
}
const codeParts = code
// Strip off the escape sequences \x1B[ and m
.slice(2, -1)
.split(";");
const ret = [];
for (let i = 0; i < codeParts.length; i++) {
const rawCode = codeParts[i];
// Keep 8-bit and 24-bit color codes (containing multiple ";") together
if (rawCode === "38" || rawCode === "48") {
if (i + 2 < codeParts.length && codeParts[i + 1] === "5") {
// 8-bit color, followed by another number
ret.push(codeParts.slice(i, i + 3).join(";"));
i += 2;
continue;
}
else if (i + 4 < codeParts.length && codeParts[i + 1] === "2") {
// 24-bit color, followed by three numbers
ret.push(codeParts.slice(i, i + 5).join(";"));
i += 4;
continue;
}
}
// Not a (valid) 8/24-bit color code, push as is
ret.push(rawCode);
}
return ret.map((part) => `\x1b[${part}m`);
}
export function tokenize(str, endChar = Number.POSITIVE_INFINITY) {
const ret = [];
let index = 0;
let visible = 0;
while (index < str.length) {
const codePoint = str.codePointAt(index);
if (ESCAPES.has(codePoint)) {
let code;
// Peek the next code point to determine the type of ANSI sequence
const nextCodePoint = str.codePointAt(index + 1);
if (nextCodePoint === OSC) {
// ] = operating system commands, like links
code = parseLinkCode(str, index);
if (code) {
ret.push({
type: "ansi",
code: code,
endCode: getEndCode(code),
});
}
}
else if (nextCodePoint === CSI) {
// [ = control sequence introducer, like SGR sequences [...m
code = parseSGRSequence(str, index);
if (code) {
// Split compound codes into individual tokens
const codes = splitCompoundSGRSequences(code);
for (const individualCode of codes) {
ret.push({
type: "ansi",
code: individualCode,
endCode: getEndCode(individualCode),
});
}
}
}
if (code) {
index += code.length;
continue;
}
}
const fullWidth = isFullwidthCodePoint(codePoint);
const character = String.fromCodePoint(codePoint);
ret.push({
type: "char",
value: character,
fullWidth,
});
index += character.length;
visible += fullWidth ? 2 : character.length;
if (visible >= endChar) {
break;
}
}
return ret;
}
//# sourceMappingURL=tokenize.js.map

View File

@@ -0,0 +1,11 @@
import { reduceAnsiCodes } from "./reduce.js";
/** Returns the combination of ANSI codes needed to undo the given ANSI codes */
export function undoAnsiCodes(codes) {
return reduceAnsiCodes(codes)
.reverse()
.map((code) => ({
...code,
code: code.endCode,
}));
}
//# sourceMappingURL=undo.js.map

View File

@@ -0,0 +1,223 @@
const tokenize = (input) => {
let current = 0;
let tokens = [];
while (current < input.length) {
let char = input[current];
if (char === '\\') {
current++;
continue;
}
if (char === '{') {
tokens.push({
type: 'brace',
value: '{',
});
current++;
continue;
}
if (char === '}') {
tokens.push({
type: 'brace',
value: '}',
});
current++;
continue;
}
if (char === '[') {
tokens.push({
type: 'paren',
value: '[',
});
current++;
continue;
}
if (char === ']') {
tokens.push({
type: 'paren',
value: ']',
});
current++;
continue;
}
if (char === ':') {
tokens.push({
type: 'separator',
value: ':',
});
current++;
continue;
}
if (char === ',') {
tokens.push({
type: 'delimiter',
value: ',',
});
current++;
continue;
}
if (char === '"') {
let value = '';
let danglingQuote = false;
char = input[++current];
while (char !== '"') {
if (current === input.length) {
danglingQuote = true;
break;
}
if (char === '\\') {
current++;
if (current === input.length) {
danglingQuote = true;
break;
}
value += char + input[current];
char = input[++current];
}
else {
value += char;
char = input[++current];
}
}
char = input[++current];
if (!danglingQuote) {
tokens.push({
type: 'string',
value,
});
}
continue;
}
let WHITESPACE = /\s/;
if (char && WHITESPACE.test(char)) {
current++;
continue;
}
let NUMBERS = /[0-9]/;
if ((char && NUMBERS.test(char)) || char === '-' || char === '.') {
let value = '';
if (char === '-') {
value += char;
char = input[++current];
}
while ((char && NUMBERS.test(char)) || char === '.') {
value += char;
char = input[++current];
}
tokens.push({
type: 'number',
value,
});
continue;
}
let LETTERS = /[a-z]/i;
if (char && LETTERS.test(char)) {
let value = '';
while (char && LETTERS.test(char)) {
if (current === input.length) {
break;
}
value += char;
char = input[++current];
}
if (value == 'true' || value == 'false' || value === 'null') {
tokens.push({
type: 'name',
value,
});
}
else {
// unknown token, e.g. `nul` which isn't quite `null`
current++;
continue;
}
continue;
}
current++;
}
return tokens;
}, strip = (tokens) => {
if (tokens.length === 0) {
return tokens;
}
let lastToken = tokens[tokens.length - 1];
switch (lastToken.type) {
case 'separator':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
case 'number':
let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1];
if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
case 'string':
let tokenBeforeTheLastToken = tokens[tokens.length - 2];
if (tokenBeforeTheLastToken?.type === 'delimiter') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') {
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
}
break;
case 'delimiter':
tokens = tokens.slice(0, tokens.length - 1);
return strip(tokens);
break;
}
return tokens;
}, unstrip = (tokens) => {
let tail = [];
tokens.map((token) => {
if (token.type === 'brace') {
if (token.value === '{') {
tail.push('}');
}
else {
tail.splice(tail.lastIndexOf('}'), 1);
}
}
if (token.type === 'paren') {
if (token.value === '[') {
tail.push(']');
}
else {
tail.splice(tail.lastIndexOf(']'), 1);
}
}
});
if (tail.length > 0) {
tail.reverse().map((item) => {
if (item === '}') {
tokens.push({
type: 'brace',
value: '}',
});
}
else if (item === ']') {
tokens.push({
type: 'paren',
value: ']',
});
}
});
}
return tokens;
}, generate = (tokens) => {
let output = '';
tokens.map((token) => {
switch (token.type) {
case 'string':
output += '"' + token.value + '"';
break;
default:
output += token.value;
break;
}
});
return output;
}, partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
export { partialParse };
//# sourceMappingURL=parser.mjs.map

View File

@@ -0,0 +1,559 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "./internal/tslib.mjs";
import { uuid4 } from "./internal/utils/uuid.mjs";
import { validatePositiveInteger, isAbsoluteURL, safeJSON } from "./internal/utils/values.mjs";
import { sleep } from "./internal/utils/sleep.mjs";
import { castToError, isAbortError } from "./internal/errors.mjs";
import { getPlatformHeaders } from "./internal/detect-platform.mjs";
import * as Shims from "./internal/shims.mjs";
import * as Opts from "./internal/request-options.mjs";
import { VERSION } from "./version.mjs";
import * as Errors from "./core/error.mjs";
import * as Pagination from "./core/pagination.mjs";
import * as Uploads from "./core/uploads.mjs";
import * as API from "./resources/index.mjs";
import { APIPromise } from "./core/api-promise.mjs";
import { Completions, } from "./resources/completions.mjs";
import { Models } from "./resources/models.mjs";
import { Beta, } from "./resources/beta/beta.mjs";
import { Messages, } from "./resources/messages/messages.mjs";
import { isRunningInBrowser } from "./internal/detect-platform.mjs";
import { buildHeaders } from "./internal/headers.mjs";
import { readEnv } from "./internal/utils/env.mjs";
import { formatRequestDetails, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs";
import { isEmptyObj } from "./internal/utils/values.mjs";
export const HUMAN_PROMPT = '\\n\\nHuman:';
export const AI_PROMPT = '\\n\\nAssistant:';
/**
* Base class for Anthropic API clients.
*/
export class BaseAnthropic {
/**
* API Client for interfacing with the Anthropic API.
*
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
*/
constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) {
_BaseAnthropic_instances.add(this);
_BaseAnthropic_encoder.set(this, void 0);
const options = {
apiKey,
authToken,
...opts,
baseURL: baseURL || `https://api.anthropic.com`,
};
if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
throw new Errors.AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
}
this.baseURL = options.baseURL;
this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
this.logger = options.logger ?? console;
const defaultLogLevel = 'warn';
// Set default logLevel early so that we can log a warning in parseLogLevel.
this.logLevel = defaultLogLevel;
this.logLevel =
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ??
defaultLogLevel;
this.fetchOptions = options.fetchOptions;
this.maxRetries = options.maxRetries ?? 2;
this.fetch = options.fetch ?? Shims.getDefaultFetch();
__classPrivateFieldSet(this, _BaseAnthropic_encoder, Opts.FallbackEncoder, "f");
this._options = options;
this.apiKey = typeof apiKey === 'string' ? apiKey : null;
this.authToken = authToken;
}
/**
* Create a new client instance re-using the same options given to the current client with optional overriding.
*/
withOptions(options) {
const client = new this.constructor({
...this._options,
baseURL: this.baseURL,
maxRetries: this.maxRetries,
timeout: this.timeout,
logger: this.logger,
logLevel: this.logLevel,
fetch: this.fetch,
fetchOptions: this.fetchOptions,
apiKey: this.apiKey,
authToken: this.authToken,
...options,
});
return client;
}
defaultQuery() {
return this._options.defaultQuery;
}
validateHeaders({ values, nulls }) {
if (values.get('x-api-key') || values.get('authorization')) {
return;
}
if (this.apiKey && values.get('x-api-key')) {
return;
}
if (nulls.has('x-api-key')) {
return;
}
if (this.authToken && values.get('authorization')) {
return;
}
if (nulls.has('authorization')) {
return;
}
throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
}
async authHeaders(opts) {
return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
}
async apiKeyAuth(opts) {
if (this.apiKey == null) {
return undefined;
}
return buildHeaders([{ 'X-Api-Key': this.apiKey }]);
}
async bearerAuth(opts) {
if (this.authToken == null) {
return undefined;
}
return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]);
}
/**
* Basic re-implementation of `qs.stringify` for primitive types.
*/
stringifyQuery(query) {
return Object.entries(query)
.filter(([_, value]) => typeof value !== 'undefined')
.map(([key, value]) => {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}
if (value === null) {
return `${encodeURIComponent(key)}=`;
}
throw new Errors.AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
})
.join('&');
}
getUserAgent() {
return `${this.constructor.name}/JS ${VERSION}`;
}
defaultIdempotencyKey() {
return `stainless-node-retry-${uuid4()}`;
}
makeStatusError(status, error, message, headers) {
return Errors.APIError.generate(status, error, message, headers);
}
buildURL(path, query, defaultBaseURL) {
const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
const url = isAbsoluteURL(path) ?
new URL(path)
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query };
}
if (typeof query === 'object' && query && !Array.isArray(query)) {
url.search = this.stringifyQuery(query);
}
return url.toString();
}
_calculateNonstreamingTimeout(maxTokens) {
const defaultTimeout = 10 * 60;
const expectedTimeout = (60 * 60 * maxTokens) / 128000;
if (expectedTimeout > defaultTimeout) {
throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' +
'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details');
}
return defaultTimeout * 1000;
}
/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
async prepareOptions(options) { }
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
async prepareRequest(request, { url, options }) { }
get(path, opts) {
return this.methodRequest('get', path, opts);
}
post(path, opts) {
return this.methodRequest('post', path, opts);
}
patch(path, opts) {
return this.methodRequest('patch', path, opts);
}
put(path, opts) {
return this.methodRequest('put', path, opts);
}
delete(path, opts) {
return this.methodRequest('delete', path, opts);
}
methodRequest(method, path, opts) {
return this.request(Promise.resolve(opts).then((opts) => {
return { method, path, ...opts };
}));
}
request(options, remainingRetries = null) {
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
}
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
const options = await optionsInput;
const maxRetries = options.maxRetries ?? this.maxRetries;
if (retriesRemaining == null) {
retriesRemaining = maxRetries;
}
await this.prepareOptions(options);
const { req, url, timeout } = await this.buildRequest(options, {
retryCount: maxRetries - retriesRemaining,
});
await this.prepareRequest(req, { url, options });
/** Not an API request ID, just for correlating local log entries. */
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
const startTime = Date.now();
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
retryOfRequestLogID,
method: options.method,
url,
options,
headers: req.headers,
}));
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
const headersTime = Date.now();
if (response instanceof globalThis.Error) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
if (options.signal?.aborted) {
throw new Errors.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 Errors.APIConnectionTimeoutError();
}
throw new Errors.APIConnectionError({ cause: response });
}
const specialHeaders = [...response.headers.entries()]
.filter(([name]) => name === 'request-id')
.map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
.join('');
const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
if (!response.ok) {
const shouldRetry = await this.shouldRetry(response);
if (retriesRemaining && shouldRetry) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
// We don't need the body of this response.
await Shims.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, opts && 'then' in opts ?
opts.then((opts) => ({ method: 'get', path, ...opts }))
: { method: 'get', path, ...opts });
}
requestAPIList(Page, options) {
const request = this.makeRequest(options, null, undefined);
return new Pagination.PagePromise(this, request, Page);
}
async fetchWithTimeout(url, init, ms, controller) {
const { signal, method, ...options } = init || {};
// Avoid creating a closure over `this`, `init`, or `options` to prevent memory leaks.
// An arrow function like `() => controller.abort()` captures the surrounding scope,
// which includes the request body and other large objects. When the user passes a
// long-lived AbortSignal, the listener prevents those objects from being GC'd for
// the lifetime of the signal. Using `.bind()` only retains a reference to the
// controller itself.
const abort = this._makeAbort(controller);
if (signal)
signal.addEventListener('abort', abort, { once: true });
const timeout = setTimeout(abort, ms);
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
const fetchOptions = {
signal: controller.signal,
...(isReadableBody ? { duplex: 'half' } : {}),
method: 'GET',
...options,
};
if (method) {
// Custom methods like 'patch' need to be uppercased
// See https://github.com/nodejs/undici/issues/2294
fetchOptions.method = method.toUpperCase();
}
try {
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
return await this.fetch.call(undefined, url, fetchOptions);
}
finally {
clearTimeout(timeout);
}
}
async shouldRetry(response) {
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true')
return true;
if (shouldRetryHeader === 'false')
return false;
// Retry on request timeouts.
if (response.status === 408)
return true;
// Retry on lock timeouts.
if (response.status === 409)
return true;
// Retry on rate limits.
if (response.status === 429)
return true;
// Retry internal errors.
if (response.status >= 500)
return true;
return false;
}
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
let timeoutMillis;
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
if (retryAfterMillisHeader) {
const timeoutMs = parseFloat(retryAfterMillisHeader);
if (!Number.isNaN(timeoutMs)) {
timeoutMillis = timeoutMs;
}
}
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
const retryAfterHeader = responseHeaders?.get('retry-after');
if (retryAfterHeader && !timeoutMillis) {
const timeoutSeconds = parseFloat(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
}
else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
// just do what it says, but otherwise calculate a default
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await sleep(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
}
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
const maxTime = 60 * 60 * 1000; // 60 minutes
const defaultTime = 60 * 10 * 1000; // 10 minutes
const expectedTime = (maxTime * maxTokens) / 128000;
if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) {
throw new Errors.AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details');
}
return defaultTime;
}
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
const options = { ...inputOptions };
const { method, path, query, defaultBaseURL } = options;
const url = this.buildURL(path, query, defaultBaseURL);
if ('timeout' in options)
validatePositiveInteger('timeout', options.timeout);
options.timeout = options.timeout ?? this.timeout;
const { bodyHeaders, body } = this.buildBody({ options });
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
const req = {
method,
headers: reqHeaders,
...(options.signal && { signal: options.signal }),
...(globalThis.ReadableStream &&
body instanceof globalThis.ReadableStream && { duplex: 'half' }),
...(body && { body }),
...(this.fetchOptions ?? {}),
...(options.fetchOptions ?? {}),
};
return { req, url, timeout: options.timeout };
}
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
let idempotencyHeaders = {};
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey)
options.idempotencyKey = this.defaultIdempotencyKey();
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
}
const headers = buildHeaders([
idempotencyHeaders,
{
Accept: 'application/json',
'User-Agent': this.getUserAgent(),
'X-Stainless-Retry-Count': String(retryCount),
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
...getPlatformHeaders(),
...(this._options.dangerouslyAllowBrowser ?
{ 'anthropic-dangerous-direct-browser-access': 'true' }
: undefined),
'anthropic-version': '2023-06-01',
},
await this.authHeaders(options),
this._options.defaultHeaders,
bodyHeaders,
options.headers,
]);
this.validateHeaders(headers);
return headers.values;
}
_makeAbort(controller) {
// note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
// would capture all request options, and cause a memory leak.
return () => controller.abort();
}
buildBody({ options: { body, headers: rawHeaders } }) {
if (!body) {
return { bodyHeaders: undefined, body: undefined };
}
const headers = buildHeaders([rawHeaders]);
if (
// Pass raw type verbatim
ArrayBuffer.isView(body) ||
body instanceof ArrayBuffer ||
body instanceof DataView ||
(typeof body === 'string' &&
// Preserve legacy string encoding behavior for now
headers.values.has('content-type')) ||
// `Blob` is superset of `File`
(globalThis.Blob && body instanceof globalThis.Blob) ||
// `FormData` -> `multipart/form-data`
body instanceof FormData ||
// `URLSearchParams` -> `application/x-www-form-urlencoded`
body instanceof URLSearchParams ||
// Send chunked stream (each chunk has own `length`)
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
return { bodyHeaders: undefined, body: body };
}
else if (typeof body === 'object' &&
(Symbol.asyncIterator in body ||
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
}
else {
return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
}
}
}
_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() {
return this.baseURL !== 'https://api.anthropic.com';
};
BaseAnthropic.Anthropic = _a;
BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT;
BaseAnthropic.AI_PROMPT = AI_PROMPT;
BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes
BaseAnthropic.AnthropicError = Errors.AnthropicError;
BaseAnthropic.APIError = Errors.APIError;
BaseAnthropic.APIConnectionError = Errors.APIConnectionError;
BaseAnthropic.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
BaseAnthropic.APIUserAbortError = Errors.APIUserAbortError;
BaseAnthropic.NotFoundError = Errors.NotFoundError;
BaseAnthropic.ConflictError = Errors.ConflictError;
BaseAnthropic.RateLimitError = Errors.RateLimitError;
BaseAnthropic.BadRequestError = Errors.BadRequestError;
BaseAnthropic.AuthenticationError = Errors.AuthenticationError;
BaseAnthropic.InternalServerError = Errors.InternalServerError;
BaseAnthropic.PermissionDeniedError = Errors.PermissionDeniedError;
BaseAnthropic.UnprocessableEntityError = Errors.UnprocessableEntityError;
BaseAnthropic.toFile = Uploads.toFile;
/**
* API Client for interfacing with the Anthropic API.
*/
export class Anthropic extends BaseAnthropic {
constructor() {
super(...arguments);
this.completions = new API.Completions(this);
this.messages = new API.Messages(this);
this.models = new API.Models(this);
this.beta = new API.Beta(this);
}
}
Anthropic.Completions = Completions;
Anthropic.Messages = Messages;
Anthropic.Models = Models;
Anthropic.Beta = Beta;
//# sourceMappingURL=client.mjs.map

View File

@@ -0,0 +1,72 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { defaultParseResponse, addRequestID, } from "../internal/parse.mjs";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export class APIPromise extends Promise {
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
_APIPromise_client.set(this, void 0);
__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response, request_id: response.headers.get('request-id') };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.mjs.map

View File

@@ -0,0 +1,98 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { castToError } from "../internal/errors.mjs";
export class AnthropicError extends Error {
}
export class APIError extends AnthropicError {
constructor(status, error, message, headers) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.requestID = headers?.get('request-id');
this.error = error;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status || !headers) {
return new APIConnectionError({ message, cause: castToError(errorResponse) });
}
const error = errorResponse;
if (status === 400) {
return new BadRequestError(status, error, message, headers);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers);
}
if (status === 409) {
return new ConflictError(status, error, message, headers);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers);
}
return new APIError(status, error, message, headers);
}
}
export class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
}
}
export 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;
}
}
export class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
export class BadRequestError extends APIError {
}
export class AuthenticationError extends APIError {
}
export class PermissionDeniedError extends APIError {
}
export class NotFoundError extends APIError {
}
export class ConflictError extends APIError {
}
export class UnprocessableEntityError extends APIError {
}
export class RateLimitError extends APIError {
}
export class InternalServerError extends APIError {
}
//# sourceMappingURL=error.mjs.map

View File

@@ -0,0 +1,177 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { defaultParseResponse } from "../internal/parse.mjs";
import { APIPromise } from "./api-promise.mjs";
import { maybeObj } from "../internal/utils/values.mjs";
export class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export class PagePromise extends APIPromise {
constructor(client, request, Page) {
super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
export class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.first_id = body.first_id || null;
this.last_id = body.last_id || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
before_id: first_id,
},
};
}
const cursor = this.last_id;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
after_id: cursor,
},
};
}
}
export class TokenPage extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page_token: cursor,
},
};
}
}
export class PageCursor extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page: cursor,
},
};
}
}
//# sourceMappingURL=pagination.mjs.map

View File

@@ -0,0 +1,7 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export class APIResource {
constructor(client) {
this._client = client;
}
}
//# sourceMappingURL=resource.mjs.map

View File

@@ -0,0 +1,283 @@
var _Stream_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { makeReadableStream } from "../internal/shims.mjs";
import { findDoubleNewlineIndex, LineDecoder } from "../internal/decoders/line.mjs";
import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs";
import { isAbortError } from "../internal/errors.mjs";
import { safeJSON } from "../internal/utils/values.mjs";
import { encodeUTF8 } from "../internal/utils/bytes.mjs";
import { loggerFor } from "../internal/utils/log.mjs";
import { APIError } from "./error.mjs";
export class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? loggerFor(client) : console;
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (sse.event === 'completion') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'message_start' ||
sse.event === 'message_delta' ||
sse.event === 'message_stop' ||
sse.event === 'content_block_start' ||
sse.event === 'content_block_delta' ||
sse.event === 'content_block_stop') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'ping') {
continue;
}
if (sse.event === 'error') {
throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);
}
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(readableStream);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
yield line;
}
}
for (const line of lineDecoder.flush()) {
yield line;
}
}
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done)
continue;
if (line)
yield JSON.parse(line);
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return {
next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
},
};
};
return [
new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return makeReadableStream({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done)
return ctrl.close();
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
ctrl.enqueue(bytes);
}
catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
},
});
}
}
export async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new AnthropicError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(response.body);
for await (const sseChunk of iterSSEChunks(iter)) {
for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) {
continue;
}
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
: typeof chunk === 'string' ? encodeUTF8(chunk)
: chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) {
yield data;
}
}
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length)
return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
}
else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, '', ''];
}
//# sourceMappingURL=streaming.mjs.map

View File

@@ -0,0 +1,2 @@
export { toFile } from "../internal/to-file.mjs";
//# sourceMappingURL=uploads.mjs.map

View File

@@ -0,0 +1,2 @@
export * from "./core/error.mjs";
//# sourceMappingURL=error.mjs.map

View File

@@ -0,0 +1,8 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export { Anthropic as default } from "./client.mjs";
export { toFile } from "./core/uploads.mjs";
export { APIPromise } from "./core/api-promise.mjs";
export { BaseAnthropic, Anthropic, HUMAN_PROMPT, AI_PROMPT } from "./client.mjs";
export { PagePromise } from "./core/pagination.mjs";
export { AnthropicError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from "./core/error.mjs";
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1,15 @@
// File containing shared constants
/**
* Model-specific timeout constraints for non-streaming requests
*/
export const MODEL_NONSTREAMING_TOKENS = {
'claude-opus-4-20250514': 8192,
'claude-opus-4-0': 8192,
'claude-4-opus-20250514': 8192,
'anthropic.claude-opus-4-20250514-v1:0': 8192,
'claude-opus-4@20250514': 8192,
'claude-opus-4-1-20250805': 8192,
'anthropic.claude-opus-4-1-20250805-v1:0': 8192,
'claude-opus-4-1@20250805': 8192,
};
//# sourceMappingURL=constants.mjs.map

View File

@@ -0,0 +1,35 @@
import { AnthropicError } from "../../core/error.mjs";
import { ReadableStreamToAsyncIterable } from "../shims.mjs";
import { LineDecoder } from "./line.mjs";
export class JSONLDecoder {
constructor(iterator, controller) {
this.iterator = iterator;
this.controller = controller;
}
async *decoder() {
const lineDecoder = new LineDecoder();
for await (const chunk of this.iterator) {
for (const line of lineDecoder.decode(chunk)) {
yield JSON.parse(line);
}
}
for (const line of lineDecoder.flush()) {
yield JSON.parse(line);
}
}
[Symbol.asyncIterator]() {
return this.decoder();
}
static fromResponse(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new AnthropicError(`Attempted to iterate over a response with no body`);
}
return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);
}
}
//# sourceMappingURL=jsonl.mjs.map

View File

@@ -0,0 +1,108 @@
var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../tslib.mjs";
import { concatBytes, decodeUTF8, encodeUTF8 } from "../utils/bytes.mjs";
/**
* 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
*/
export 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' ? encodeUTF8(chunk)
: chunk;
__classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f");
const lines = [];
let patternIndex;
while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
// skip until we either get a corresponding `\n`, a new `\r` or nothing
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
continue;
}
// we got double \r or \rtext\n
if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null &&
(patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
__classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f");
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
continue;
}
const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
lines.push(line);
__classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f");
__classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f");
}
return lines;
}
flush() {
if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
return [];
}
return this.decode('\n');
}
}
_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap();
// prettier-ignore
LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
/**
* This function searches the buffer for the end patterns, (\r or \n)
* and returns an object with the index preceding the matched newline and the
* index after the newline char. `null` is returned if no new line is found.
*
* ```ts
* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
* ```
*/
function findNewlineIndex(buffer, startIndex) {
const newline = 0x0a; // \n
const carriage = 0x0d; // \r
for (let i = startIndex ?? 0; i < buffer.length; i++) {
if (buffer[i] === newline) {
return { preceding: i, index: i + 1, carriage: false };
}
if (buffer[i] === carriage) {
return { preceding: i, index: i + 1, carriage: true };
}
}
return null;
}
export 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

View File

@@ -0,0 +1,157 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { VERSION } from "../version.mjs";
export const isRunningInBrowser = () => {
return (
// @ts-ignore
typeof window !== 'undefined' &&
// @ts-ignore
typeof window.document !== 'undefined' &&
// @ts-ignore
typeof navigator !== 'undefined');
};
/**
* Note this does not detect 'browser'; for that, use getBrowserInfo().
*/
function getDetectedPlatform() {
if (typeof Deno !== 'undefined' && Deno.build != null) {
return 'deno';
}
if (typeof EdgeRuntime !== 'undefined') {
return 'edge';
}
if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
return 'node';
}
return 'unknown';
}
const getPlatformProperties = () => {
const detectedPlatform = getDetectedPlatform();
if (detectedPlatform === 'deno') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': normalizePlatform(Deno.build.os),
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
'X-Stainless-Runtime': 'deno',
'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',
};
}
if (typeof EdgeRuntime !== 'undefined') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': `other:${EdgeRuntime}`,
'X-Stainless-Runtime': 'edge',
'X-Stainless-Runtime-Version': globalThis.process.version,
};
}
// Check if Node.js
if (detectedPlatform === 'node') {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'),
'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'),
'X-Stainless-Runtime': 'node',
'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown',
};
}
const browserInfo = getBrowserInfo();
if (browserInfo) {
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': 'unknown',
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
'X-Stainless-Runtime-Version': browserInfo.version,
};
}
// TODO add support for Cloudflare workers, etc.
return {
'X-Stainless-Lang': 'js',
'X-Stainless-Package-Version': VERSION,
'X-Stainless-OS': 'Unknown',
'X-Stainless-Arch': 'unknown',
'X-Stainless-Runtime': 'unknown',
'X-Stainless-Runtime-Version': 'unknown',
};
};
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
function getBrowserInfo() {
if (typeof navigator === 'undefined' || !navigator) {
return null;
}
// NOTE: The order matters here!
const browserPatterns = [
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
];
// Find the FIRST matching browser
for (const { key, pattern } of browserPatterns) {
const match = pattern.exec(navigator.userAgent);
if (match) {
const major = match[1] || 0;
const minor = match[2] || 0;
const patch = match[3] || 0;
return { browser: key, version: `${major}.${minor}.${patch}` };
}
}
return null;
}
const normalizeArch = (arch) => {
// Node docs:
// - https://nodejs.org/api/process.html#processarch
// Deno docs:
// - https://doc.deno.land/deno/stable/~/Deno.build
if (arch === 'x32')
return 'x32';
if (arch === 'x86_64' || arch === 'x64')
return 'x64';
if (arch === 'arm')
return 'arm';
if (arch === 'aarch64' || arch === 'arm64')
return 'arm64';
if (arch)
return `other:${arch}`;
return 'unknown';
};
const normalizePlatform = (platform) => {
// Node platforms:
// - https://nodejs.org/api/process.html#processplatform
// Deno platforms:
// - https://doc.deno.land/deno/stable/~/Deno.build
// - https://github.com/denoland/deno/issues/14799
platform = platform.toLowerCase();
// NOTE: this iOS check is untested and may not work
// Node does not work natively on IOS, there is a fork at
// https://github.com/nodejs-mobile/nodejs-mobile
// however it is unknown at the time of writing how to detect if it is running
if (platform.includes('ios'))
return 'iOS';
if (platform === 'android')
return 'Android';
if (platform === 'darwin')
return 'MacOS';
if (platform === 'win32')
return 'Windows';
if (platform === 'freebsd')
return 'FreeBSD';
if (platform === 'openbsd')
return 'OpenBSD';
if (platform === 'linux')
return 'Linux';
if (platform)
return `Other:${platform}`;
return 'Unknown';
};
let _platformHeaders;
export const getPlatformHeaders = () => {
return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));
};
//# sourceMappingURL=detect-platform.mjs.map

View File

@@ -0,0 +1,36 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export 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'))));
}
export const castToError = (err) => {
if (err instanceof Error)
return err;
if (typeof err === 'object' && err !== null) {
try {
if (Object.prototype.toString.call(err) === '[object Error]') {
// @ts-ignore - not all envs have native support for cause yet
const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
if (err.stack)
error.stack = err.stack;
// @ts-ignore - not all envs have native support for cause yet
if (err.cause && !error.cause)
error.cause = err.cause;
if (err.name)
error.name = err.name;
return error;
}
}
catch { }
try {
return new Error(JSON.stringify(err));
}
catch { }
}
return new Error(err);
};
//# sourceMappingURL=errors.mjs.map

View File

@@ -0,0 +1,74 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { isReadonlyArray } from "./utils/values.mjs";
const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders');
function* iterateHeaders(headers) {
if (!headers)
return;
if (brand_privateNullableHeaders in headers) {
const { values, nulls } = headers;
yield* values.entries();
for (const name of nulls) {
yield [name, null];
}
return;
}
let shouldClear = false;
let iter;
if (headers instanceof Headers) {
iter = headers.entries();
}
else if (isReadonlyArray(headers)) {
iter = headers;
}
else {
shouldClear = true;
iter = Object.entries(headers ?? {});
}
for (let row of iter) {
const name = row[0];
if (typeof name !== 'string')
throw new TypeError('expected header name to be a string');
const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
let didClear = false;
for (const value of values) {
if (value === undefined)
continue;
// Objects keys always overwrite older headers, they never append.
// Yield a null to clear the header before adding the new values.
if (shouldClear && !didClear) {
didClear = true;
yield [name, null];
}
yield [name, value];
}
}
}
export 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 };
};
export const isEmptyHeaders = (headers) => {
for (const _ of iterateHeaders(headers))
return false;
return true;
};
//# sourceMappingURL=headers.mjs.map

View File

@@ -0,0 +1,56 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { Stream } from "../core/streaming.mjs";
import { formatRequestDetails, loggerFor } from "./utils/log.mjs";
export 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<T>`
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 contentLength = response.headers.get('content-length');
if (contentLength === '0') {
// if there is no content we can't do anything
return undefined;
}
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;
}
export function addRequestID(value, response) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return value;
}
return Object.defineProperty(value, '_request_id', {
value: response.headers.get('request-id'),
enumerable: false,
});
}
//# sourceMappingURL=parse.mjs.map

View File

@@ -0,0 +1,10 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export const FallbackEncoder = ({ headers, body }) => {
return {
bodyHeaders: {
'content-type': 'application/json',
},
body: JSON.stringify(body),
};
};
//# sourceMappingURL=request-options.mjs.map

View File

@@ -0,0 +1,85 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export function getDefaultFetch() {
if (typeof fetch !== 'undefined') {
return fetch;
}
throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');
}
export function makeReadableStream(...args) {
const ReadableStream = globalThis.ReadableStream;
if (typeof ReadableStream === 'undefined') {
// Note: All of the platforms / runtimes we officially support already define
// `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
}
return new ReadableStream(...args);
}
export function ReadableStreamFrom(iterable) {
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
return makeReadableStream({
start() { },
async pull(controller) {
const { done, value } = await iter.next();
if (done) {
controller.close();
}
else {
controller.enqueue(value);
}
},
async cancel() {
await iter.return?.();
},
});
}
/**
* Most browsers don't yet have async iterable support for ReadableStream,
* and Node has a very different way of reading bytes from its "ReadableStream".
*
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
*/
export 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
*/
export async function CancelReadableStream(stream) {
if (stream === null || typeof stream !== 'object')
return;
if (stream[Symbol.asyncIterator]) {
await stream[Symbol.asyncIterator]().return?.();
return;
}
const reader = stream.getReader();
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
}
//# sourceMappingURL=shims.mjs.map

View File

@@ -0,0 +1,93 @@
import { getName, makeFile, isAsyncIterable } from "./uploads.mjs";
import { checkFileSupport } from "./uploads.mjs";
/**
* This check adds the arrayBuffer() method type because it is available and used at runtime
*/
const isBlobLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.size === 'number' &&
typeof value.type === 'string' &&
typeof value.text === 'function' &&
typeof value.slice === 'function' &&
typeof value.arrayBuffer === 'function';
/**
* This check adds the arrayBuffer() method type because it is available and used at runtime
*/
const isFileLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.name === 'string' &&
typeof value.lastModified === 'number' &&
isBlobLike(value);
const isResponseLike = (value) => value != null &&
typeof value === 'object' &&
typeof value.url === 'string' &&
typeof value.blob === 'function';
/**
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
* @param {Object=} options additional properties
* @param {string=} options.type the MIME type of the content
* @param {number=} options.lastModified the last modified timestamp
* @returns a {@link File} with the given properties
*/
export async function toFile(value, name, options) {
checkFileSupport();
// If it's a promise, resolve it.
value = await value;
name || (name = getName(value, true));
// If we've been given a `File` we don't need to do anything if the name / options
// have not been customised.
if (isFileLike(value)) {
if (value instanceof File && name == null && options == null) {
return value;
}
return makeFile([await value.arrayBuffer()], name ?? value.name, {
type: value.type,
lastModified: value.lastModified,
...options,
});
}
if (isResponseLike(value)) {
const blob = await value.blob();
name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
return makeFile(await getBytes(blob), name, options);
}
const parts = await getBytes(value);
if (!options?.type) {
const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
if (typeof type === 'string') {
options = { ...options, type };
}
}
return makeFile(parts, name, options);
}
async function getBytes(value) {
let parts = [];
if (typeof value === 'string' ||
ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
value instanceof ArrayBuffer) {
parts.push(value);
}
else if (isBlobLike(value)) {
parts.push(value instanceof Blob ? value : await value.arrayBuffer());
}
else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.
) {
for await (const chunk of value) {
parts.push(...(await getBytes(chunk))); // TODO, consider validating?
}
}
else {
const constructor = value?.constructor?.name;
throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
}
return parts;
}
function propsForError(value) {
if (typeof value !== 'object' || value === null)
return '';
const props = Object.getOwnPropertyNames(value);
return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
}
//# sourceMappingURL=to-file.mjs.map

View File

@@ -0,0 +1,17 @@
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);
}
export { __classPrivateFieldSet, __classPrivateFieldGet };

View File

@@ -0,0 +1,135 @@
import { ReadableStreamFrom } from "./shims.mjs";
export 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.
*/
export function makeFile(fileBits, fileName, options) {
checkFileSupport();
return new File(fileBits, fileName ?? 'unknown_file', options);
}
export function getName(value, stripPath) {
const val = (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)))) ||
'';
return stripPath ? val.split(/[\\/]/).pop() || undefined : val;
}
export const 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.
*/
export const maybeMultipartFormRequestOptions = async (opts, fetch) => {
if (!hasUploadableValue(opts.body))
return opts;
return { ...opts, body: await createForm(opts.body, fetch) };
};
export const multipartFormRequestOptions = async (opts, fetch, stripFilenames = true) => {
return { ...opts, body: await createForm(opts.body, fetch, stripFilenames) };
};
const supportsFormDataMap = /* @__PURE__ */ new WeakMap();
/**
* node-fetch doesn't support the global FormData object in recent node versions. Instead of sending
* properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]".
* This function detects if the fetch function provided supports the global FormData object to avoid
* confusing error messages later on.
*/
function supportsFormData(fetchObject) {
const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch;
const cached = supportsFormDataMap.get(fetch);
if (cached)
return cached;
const promise = (async () => {
try {
const FetchResponse = ('Response' in fetch ?
fetch.Response
: (await fetch('data:,')).constructor);
const data = new FormData();
if (data.toString() === (await new FetchResponse(data).text())) {
return false;
}
return true;
}
catch {
// avoid false negatives
return true;
}
})();
supportsFormDataMap.set(fetch, promise);
return promise;
}
export const createForm = async (body, fetch, stripFilenames = true) => {
if (!(await supportsFormData(fetch))) {
throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.');
}
const form = new FormData();
await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames)));
return form;
};
// We check for Blob not File because Bun.File doesn't inherit from File,
// but they both inherit from Blob and have a `name` property at runtime.
const isNamedBlob = (value) => value instanceof Blob && 'name' in value;
const isUploadable = (value) => typeof value === 'object' &&
value !== null &&
(value instanceof Response || isAsyncIterable(value) || isNamedBlob(value));
const hasUploadableValue = (value) => {
if (isUploadable(value))
return true;
if (Array.isArray(value))
return value.some(hasUploadableValue);
if (value && typeof value === 'object') {
for (const k in value) {
if (hasUploadableValue(value[k]))
return true;
}
}
return false;
};
const addFormValue = async (form, key, value, stripFilenames) => {
if (value === undefined)
return;
if (value == null) {
throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
}
// TODO: make nested formats configurable
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
form.append(key, String(value));
}
else if (value instanceof Response) {
let options = {};
const contentType = value.headers.get('Content-Type');
if (contentType) {
options = { type: contentType };
}
form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options));
}
else if (isAsyncIterable(value)) {
form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames)));
}
else if (isNamedBlob(value)) {
form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type }));
}
else if (Array.isArray(value)) {
await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry, stripFilenames)));
}
else if (typeof value === 'object') {
await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames)));
}
else {
throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
}
};
//# sourceMappingURL=uploads.mjs.map

View File

@@ -0,0 +1,26 @@
export function concatBytes(buffers) {
let length = 0;
for (const buffer of buffers) {
length += buffer.length;
}
const output = new Uint8Array(length);
let index = 0;
for (const buffer of buffers) {
output.set(buffer, index);
index += buffer.length;
}
return output;
}
let encodeUTF8_;
export function encodeUTF8(str) {
let encoder;
return (encodeUTF8_ ??
((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
}
let decodeUTF8_;
export function decodeUTF8(bytes) {
let decoder;
return (decodeUTF8_ ??
((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
}
//# sourceMappingURL=bytes.mjs.map

View File

@@ -0,0 +1,18 @@
// 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.
*/
export 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

View File

@@ -0,0 +1,80 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { hasOwn } from "./values.mjs";
const levelNumbers = {
off: 0,
error: 200,
warn: 300,
info: 400,
debug: 500,
};
export 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();
export 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;
}
export const formatRequestDetails = (details) => {
if (details.options) {
details.options = { ...details.options };
delete details.options['headers']; // redundant + leaks internals
}
if (details.headers) {
details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
name,
(name.toLowerCase() === 'x-api-key' ||
name.toLowerCase() === 'authorization' ||
name.toLowerCase() === 'cookie' ||
name.toLowerCase() === 'set-cookie') ?
'***'
: value,
]));
}
if ('retryOfRequestLogID' in details) {
if (details.retryOfRequestLogID) {
details.retryOf = details.retryOfRequestLogID;
}
delete details.retryOfRequestLogID;
}
return details;
};
//# sourceMappingURL=log.mjs.map

View File

@@ -0,0 +1,74 @@
import { AnthropicError } from "../../core/error.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 / ":" / "@"
*/
export function encodeURIPath(str) {
return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
export const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) {
// If there are no params, no processing is needed.
if (statics.length === 1)
return statics[0];
let postPath = false;
const invalidSegments = [];
const path = statics.reduce((previousValue, currentValue, index) => {
if (/[?#]/.test(currentValue)) {
postPath = true;
}
const value = params[index];
let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
if (index !== params.length &&
(value == null ||
(typeof value === 'object' &&
// handle values from other realms
value.toString ===
Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)
?.toString))) {
encoded = value + '';
invalidSegments.push({
start: previousValue.length + currentValue.length,
length: encoded.length,
error: `Value of type ${Object.prototype.toString
.call(value)
.slice(8, -1)} is not a valid path parameter`,
});
}
return previousValue + currentValue + (index === params.length ? '' : encoded);
}, '');
const pathOnly = path.split(/[?#]/, 1)[0];
const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
let match;
// Find all invalid segments
while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
invalidSegments.push({
start: match.index,
length: match[0].length,
error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
});
}
invalidSegments.sort((a, b) => a.start - b.start);
if (invalidSegments.length > 0) {
let lastEnd = 0;
const underline = invalidSegments.reduce((acc, segment) => {
const spaces = ' '.repeat(segment.start - lastEnd);
const arrows = '^'.repeat(segment.length);
lastEnd = segment.start + segment.length;
return acc + spaces + arrows;
}, '');
throw new 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.
*/
export const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
//# sourceMappingURL=path.mjs.map

View File

@@ -0,0 +1,3 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
//# sourceMappingURL=sleep.mjs.map

View File

@@ -0,0 +1,15 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
/**
* https://stackoverflow.com/a/2117523
*/
export let uuid4 = function () {
const { crypto } = globalThis;
if (crypto?.randomUUID) {
uuid4 = crypto.randomUUID.bind(crypto);
return crypto.randomUUID();
}
const u8 = new Uint8Array(1);
const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
};
//# sourceMappingURL=uuid.mjs.map

View File

@@ -0,0 +1,100 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { AnthropicError } from "../../core/error.mjs";
// https://url.spec.whatwg.org/#url-scheme-string
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
export const isAbsoluteURL = (url) => {
return startsWithSchemeRegexp.test(url);
};
export let isArray = (val) => ((isArray = Array.isArray), isArray(val));
export let isReadonlyArray = isArray;
/** Returns an object if the given value isn't an object, otherwise returns as-is */
export function maybeObj(x) {
if (typeof x !== 'object') {
return {};
}
return x ?? {};
}
// https://stackoverflow.com/a/34491287
export function isEmptyObj(obj) {
if (!obj)
return true;
for (const _k in obj)
return false;
return true;
}
// https://eslint.org/docs/latest/rules/no-prototype-builtins
export function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
export function isObj(obj) {
return obj != null && typeof obj === 'object' && !Array.isArray(obj);
}
export const ensurePresent = (value) => {
if (value == null) {
throw new AnthropicError(`Expected a value to be given but received ${value} instead.`);
}
return value;
};
export const validatePositiveInteger = (name, n) => {
if (typeof n !== 'number' || !Number.isInteger(n)) {
throw new AnthropicError(`${name} must be an integer`);
}
if (n < 0) {
throw new AnthropicError(`${name} must be a positive integer`);
}
return n;
};
export const coerceInteger = (value) => {
if (typeof value === 'number')
return Math.round(value);
if (typeof value === 'string')
return parseInt(value, 10);
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
export const coerceFloat = (value) => {
if (typeof value === 'number')
return value;
if (typeof value === 'string')
return parseFloat(value);
throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`);
};
export const coerceBoolean = (value) => {
if (typeof value === 'boolean')
return value;
if (typeof value === 'string')
return value === 'true';
return Boolean(value);
};
export const maybeCoerceInteger = (value) => {
if (value == null) {
return undefined;
}
return coerceInteger(value);
};
export const maybeCoerceFloat = (value) => {
if (value == null) {
return undefined;
}
return coerceFloat(value);
};
export const maybeCoerceBoolean = (value) => {
if (value == null) {
return undefined;
}
return coerceBoolean(value);
};
export const safeJSON = (text) => {
try {
return JSON.parse(text);
}
catch (err) {
return undefined;
}
};
// Gets a value from an object, deletes the key, and returns the value (or undefined if not found)
export const pop = (obj, key) => {
const value = obj[key];
delete obj[key];
return value;
};
//# sourceMappingURL=values.mjs.map

View File

@@ -0,0 +1,616 @@
var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { partialParse } from "../_vendor/partial-json-parser/parser.mjs";
import { AnthropicError, APIUserAbortError } from "../error.mjs";
import { isAbortError } from "../internal/errors.mjs";
import { Stream } from "../streaming.mjs";
import { maybeParseBetaMessage } from "./beta-parser.mjs";
const JSON_BUF_PROPERTY = '__json_buf';
function tracksToolInput(content) {
return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use';
}
export class BetaMessageStream {
constructor(params, opts) {
_BetaMessageStream_instances.add(this);
this.messages = [];
this.receivedMessages = [];
_BetaMessageStream_currentMessageSnapshot.set(this, void 0);
_BetaMessageStream_params.set(this, null);
this.controller = new AbortController();
_BetaMessageStream_connectedPromise.set(this, void 0);
_BetaMessageStream_resolveConnectedPromise.set(this, () => { });
_BetaMessageStream_rejectConnectedPromise.set(this, () => { });
_BetaMessageStream_endPromise.set(this, void 0);
_BetaMessageStream_resolveEndPromise.set(this, () => { });
_BetaMessageStream_rejectEndPromise.set(this, () => { });
_BetaMessageStream_listeners.set(this, {});
_BetaMessageStream_ended.set(this, false);
_BetaMessageStream_errored.set(this, false);
_BetaMessageStream_aborted.set(this, false);
_BetaMessageStream_catchingPromiseCreated.set(this, false);
_BetaMessageStream_response.set(this, void 0);
_BetaMessageStream_request_id.set(this, void 0);
_BetaMessageStream_logger.set(this, void 0);
_BetaMessageStream_handleError.set(this, (error) => {
__classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f");
if (isAbortError(error)) {
error = new APIUserAbortError();
}
if (error instanceof APIUserAbortError) {
__classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f");
return this._emit('abort', error);
}
if (error instanceof AnthropicError) {
return this._emit('error', error);
}
if (error instanceof Error) {
const anthropicError = new AnthropicError(error.message);
// @ts-ignore
anthropicError.cause = error;
return this._emit('error', anthropicError);
}
return this._emit('error', new AnthropicError(String(error)));
});
__classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
__classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
}), "f");
__classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
__classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f");
}), "f");
// Don't let these promises cause unhandled rejection errors.
// we will manually cause an unhandled rejection error later
// if the user hasn't registered any error listener or called
// any promise-returning method.
__classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { });
__classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { });
__classPrivateFieldSet(this, _BetaMessageStream_params, params, "f");
__classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f");
}
get response() {
return __classPrivateFieldGet(this, _BetaMessageStream_response, "f");
}
get request_id() {
return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f");
}
/**
* Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
* returned vie the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* This is the same as the `APIPromise.withResponse()` method.
*
* This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
* as no `Response` is available.
*/
async withResponse() {
__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f");
if (!response) {
throw new Error('Could not resolve a `Response` object');
}
return {
data: this,
response,
request_id: response.headers.get('request-id'),
};
}
/**
* Intended for use on the frontend, consuming a stream produced with
* `.toReadableStream()` on the backend.
*
* Note that messages sent to the model do not appear in `.on('message')`
* in this context.
*/
static fromReadableStream(stream) {
const runner = new BetaMessageStream(null);
runner._run(() => runner._fromReadableStream(stream));
return runner;
}
static createMessage(messages, params, options, { logger } = {}) {
const runner = new BetaMessageStream(params, { logger });
for (const message of params.messages) {
runner._addMessageParam(message);
}
__classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f");
runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));
return runner;
}
_run(executor) {
executor().then(() => {
this._emitFinal();
this._emit('end');
}, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f"));
}
_addMessageParam(message) {
this.messages.push(message);
}
_addMessage(message, emit = true) {
this.receivedMessages.push(message);
if (emit) {
this._emit('message', message);
}
}
async _createMessage(messages, params, options) {
const signal = options?.signal;
let abortHandler;
if (signal) {
if (signal.aborted)
this.controller.abort();
abortHandler = this.controller.abort.bind(this.controller);
signal.addEventListener('abort', abortHandler);
}
try {
__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
const { response, data: stream } = await messages
.create({ ...params, stream: true }, { ...options, signal: this.controller.signal })
.withResponse();
this._connected(response);
for await (const event of stream) {
__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
}
finally {
if (signal && abortHandler) {
signal.removeEventListener('abort', abortHandler);
}
}
}
_connected(response) {
if (this.ended)
return;
__classPrivateFieldSet(this, _BetaMessageStream_response, response, "f");
__classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f");
__classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
this._emit('connect');
}
get ended() {
return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f");
}
get errored() {
return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f");
}
get aborted() {
return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f");
}
abort() {
this.controller.abort();
}
/**
* Adds the listener function to the end of the listeners array for the event.
* No checks are made to see if the listener has already been added. Multiple calls passing
* the same combination of event and listener will result in the listener being added, and
* called, multiple times.
* @returns this MessageStream, so that calls can be chained
*/
on(event, listener) {
const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
listeners.push({ listener });
return this;
}
/**
* Removes the specified listener from the listener array for the event.
* off() will remove, at most, one instance of a listener from the listener array. If any single
* listener has been added multiple times to the listener array for the specified event, then
* off() must be called multiple times to remove each instance.
* @returns this MessageStream, so that calls can be chained
*/
off(event, listener) {
const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
if (!listeners)
return this;
const index = listeners.findIndex((l) => l.listener === listener);
if (index >= 0)
listeners.splice(index, 1);
return this;
}
/**
* Adds a one-time listener function for the event. The next time the event is triggered,
* this listener is removed and then invoked.
* @returns this MessageStream, so that calls can be chained
*/
once(event, listener) {
const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []);
listeners.push({ listener, once: true });
return this;
}
/**
* This is similar to `.once()`, but returns a Promise that resolves the next time
* the event is triggered, instead of calling a listener callback.
* @returns a Promise that resolves the next time given event is triggered,
* or rejects if an error is emitted. (If you request the 'error' event,
* returns a promise that resolves with the error).
*
* Example:
*
* const message = await stream.emitted('message') // rejects if the stream errors
*/
emitted(event) {
return new Promise((resolve, reject) => {
__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
if (event !== 'error')
this.once('error', reject);
this.once(event, resolve);
});
}
async done() {
__classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f");
}
get currentMessage() {
return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
}
/**
* @returns a promise that resolves with the the final assistant Message response,
* or rejects if an error occurred or the stream ended prematurely without producing a Message.
* If structured outputs were used, this will be a ParsedMessage with a `parsed` field.
*/
async finalMessage() {
await this.done();
return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
}
/**
* @returns a promise that resolves with the the final assistant Message's text response, concatenated
* together if there are more than one text blocks.
* Rejects if an error occurred or the stream ended prematurely without producing a Message.
*/
async finalText() {
await this.done();
return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
}
_emit(event, ...args) {
// make sure we don't emit any MessageStreamEvents after end
if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f"))
return;
if (event === 'end') {
__classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f");
__classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
}
const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event];
if (listeners) {
__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
listeners.forEach(({ listener }) => listener(...args));
}
if (event === 'abort') {
const error = args[0];
if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
this._emit('end');
return;
}
if (event === 'error') {
// NOTE: _emit('error', error) should only be called from #handleError().
const error = args[0];
if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
// Trigger an unhandled rejection if the user hasn't registered any error handlers.
// If you are seeing stack traces here, make sure to handle errors via either:
// - runner.on('error', () => ...)
// - await runner.done()
// - await runner.final...()
// - etc.
Promise.reject(error);
}
__classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
this._emit('end');
}
}
_emitFinal() {
const finalMessage = this.receivedMessages.at(-1);
if (finalMessage) {
this._emit('finalMessage', __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
}
}
async _fromReadableStream(readableStream, options) {
const signal = options?.signal;
let abortHandler;
if (signal) {
if (signal.aborted)
this.controller.abort();
abortHandler = this.controller.abort.bind(this.controller);
signal.addEventListener('abort', abortHandler);
}
try {
__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
this._connected(null);
const stream = Stream.fromReadableStream(readableStream, this.controller);
for await (const event of stream) {
__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
}
finally {
if (signal && abortHandler) {
signal.removeEventListener('abort', abortHandler);
}
}
}
[(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_params = 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_logger = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() {
if (this.receivedMessages.length === 0) {
throw new AnthropicError('stream ended without producing a Message with role=assistant');
}
return this.receivedMessages.at(-1);
}, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() {
if (this.receivedMessages.length === 0) {
throw new AnthropicError('stream ended without producing a Message with role=assistant');
}
const textBlocks = this.receivedMessages
.at(-1)
.content.filter((block) => block.type === 'text')
.map((block) => block.text);
if (textBlocks.length === 0) {
throw new AnthropicError('stream ended without producing a content block with type=text');
}
return textBlocks.join(' ');
}, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() {
if (this.ended)
return;
__classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f");
}, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) {
if (this.ended)
return;
const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
this._emit('streamEvent', event, messageSnapshot);
switch (event.type) {
case 'content_block_delta': {
const content = messageSnapshot.content.at(-1);
switch (event.delta.type) {
case 'text_delta': {
if (content.type === 'text') {
this._emit('text', event.delta.text, content.text || '');
}
break;
}
case 'citations_delta': {
if (content.type === 'text') {
this._emit('citation', event.delta.citation, content.citations ?? []);
}
break;
}
case 'input_json_delta': {
if (tracksToolInput(content) && content.input) {
this._emit('inputJson', event.delta.partial_json, content.input);
}
break;
}
case 'thinking_delta': {
if (content.type === 'thinking') {
this._emit('thinking', event.delta.thinking, content.thinking);
}
break;
}
case 'signature_delta': {
if (content.type === 'thinking') {
this._emit('signature', content.signature);
}
break;
}
case 'compaction_delta': {
if (content.type === 'compaction' && content.content) {
this._emit('compaction', content.content);
}
break;
}
default:
checkNever(event.delta);
}
break;
}
case 'message_stop': {
this._addMessageParam(messageSnapshot);
this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true);
break;
}
case 'content_block_stop': {
this._emit('contentBlock', messageSnapshot.content.at(-1));
break;
}
case 'message_start': {
__classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
break;
}
case 'content_block_start':
case 'message_delta':
break;
}
}, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() {
if (this.ended) {
throw new AnthropicError(`stream has ended, this shouldn't happen`);
}
const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
if (!snapshot) {
throw new AnthropicError(`request ended without sending any chunks`);
}
__classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f");
return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") });
}, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) {
let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f");
if (event.type === 'message_start') {
if (snapshot) {
throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
}
return event.message;
}
if (!snapshot) {
throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
}
switch (event.type) {
case 'message_stop':
return snapshot;
case 'message_delta':
snapshot.container = event.delta.container;
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
snapshot.context_management = event.context_management;
if (event.usage.input_tokens != null) {
snapshot.usage.input_tokens = event.usage.input_tokens;
}
if (event.usage.cache_creation_input_tokens != null) {
snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
}
if (event.usage.cache_read_input_tokens != null) {
snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
}
if (event.usage.server_tool_use != null) {
snapshot.usage.server_tool_use = event.usage.server_tool_use;
}
if (event.usage.iterations != null) {
snapshot.usage.iterations = event.usage.iterations;
}
return snapshot;
case 'content_block_start':
snapshot.content.push(event.content_block);
return snapshot;
case 'content_block_delta': {
const snapshotContent = snapshot.content.at(event.index);
switch (event.delta.type) {
case 'text_delta': {
if (snapshotContent?.type === 'text') {
snapshot.content[event.index] = {
...snapshotContent,
text: (snapshotContent.text || '') + event.delta.text,
};
}
break;
}
case 'citations_delta': {
if (snapshotContent?.type === 'text') {
snapshot.content[event.index] = {
...snapshotContent,
citations: [...(snapshotContent.citations ?? []), event.delta.citation],
};
}
break;
}
case 'input_json_delta': {
if (snapshotContent && tracksToolInput(snapshotContent)) {
// we need to keep track of the raw JSON string as well so that we can
// re-parse it for each delta, for now we just store it as an untyped
// non-enumerable property on the snapshot
let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || '';
jsonBuf += event.delta.partial_json;
const newContent = { ...snapshotContent };
Object.defineProperty(newContent, JSON_BUF_PROPERTY, {
value: jsonBuf,
enumerable: false,
writable: true,
});
if (jsonBuf) {
try {
newContent.input = partialParse(jsonBuf);
}
catch (err) {
const error = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
__classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error);
}
}
snapshot.content[event.index] = newContent;
}
break;
}
case 'thinking_delta': {
if (snapshotContent?.type === 'thinking') {
snapshot.content[event.index] = {
...snapshotContent,
thinking: snapshotContent.thinking + event.delta.thinking,
};
}
break;
}
case 'signature_delta': {
if (snapshotContent?.type === 'thinking') {
snapshot.content[event.index] = {
...snapshotContent,
signature: event.delta.signature,
};
}
break;
}
case 'compaction_delta': {
if (snapshotContent?.type === 'compaction') {
snapshot.content[event.index] = {
...snapshotContent,
content: (snapshotContent.content || '') + event.delta.content,
};
}
break;
}
default:
checkNever(event.delta);
}
return snapshot;
}
case 'content_block_stop':
return snapshot;
}
}, Symbol.asyncIterator)]() {
const pushQueue = [];
const readQueue = [];
let done = false;
this.on('streamEvent', (event) => {
const reader = readQueue.shift();
if (reader) {
reader.resolve(event);
}
else {
pushQueue.push(event);
}
});
this.on('end', () => {
done = true;
for (const reader of readQueue) {
reader.resolve(undefined);
}
readQueue.length = 0;
});
this.on('abort', (err) => {
done = true;
for (const reader of readQueue) {
reader.reject(err);
}
readQueue.length = 0;
});
this.on('error', (err) => {
done = true;
for (const reader of readQueue) {
reader.reject(err);
}
readQueue.length = 0;
});
return {
next: async () => {
if (!pushQueue.length) {
if (done) {
return { value: undefined, done: true };
}
return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));
}
const chunk = pushQueue.shift();
return { value: chunk, done: false };
},
return: async () => {
this.abort();
return { value: undefined, done: true };
},
};
}
toReadableStream() {
const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
return stream.toReadableStream();
}
}
// used to ensure exhaustive case matching without throwing a runtime error
function checkNever(x) { }
//# sourceMappingURL=BetaMessageStream.mjs.map

View File

@@ -0,0 +1,591 @@
var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _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_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { isAbortError } from "../internal/errors.mjs";
import { AnthropicError, APIUserAbortError } from "../error.mjs";
import { Stream } from "../streaming.mjs";
import { partialParse } from "../_vendor/partial-json-parser/parser.mjs";
import { maybeParseMessage } from "./parser.mjs";
const JSON_BUF_PROPERTY = '__json_buf';
function tracksToolInput(content) {
return content.type === 'tool_use' || content.type === 'server_tool_use';
}
export class MessageStream {
constructor(params, opts) {
_MessageStream_instances.add(this);
this.messages = [];
this.receivedMessages = [];
_MessageStream_currentMessageSnapshot.set(this, void 0);
_MessageStream_params.set(this, null);
this.controller = new AbortController();
_MessageStream_connectedPromise.set(this, void 0);
_MessageStream_resolveConnectedPromise.set(this, () => { });
_MessageStream_rejectConnectedPromise.set(this, () => { });
_MessageStream_endPromise.set(this, void 0);
_MessageStream_resolveEndPromise.set(this, () => { });
_MessageStream_rejectEndPromise.set(this, () => { });
_MessageStream_listeners.set(this, {});
_MessageStream_ended.set(this, false);
_MessageStream_errored.set(this, false);
_MessageStream_aborted.set(this, false);
_MessageStream_catchingPromiseCreated.set(this, false);
_MessageStream_response.set(this, void 0);
_MessageStream_request_id.set(this, void 0);
_MessageStream_logger.set(this, void 0);
_MessageStream_handleError.set(this, (error) => {
__classPrivateFieldSet(this, _MessageStream_errored, true, "f");
if (isAbortError(error)) {
error = new APIUserAbortError();
}
if (error instanceof APIUserAbortError) {
__classPrivateFieldSet(this, _MessageStream_aborted, true, "f");
return this._emit('abort', error);
}
if (error instanceof AnthropicError) {
return this._emit('error', error);
}
if (error instanceof Error) {
const anthropicError = new AnthropicError(error.message);
// @ts-ignore
anthropicError.cause = error;
return this._emit('error', anthropicError);
}
return this._emit('error', new AnthropicError(String(error)));
});
__classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f");
__classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f");
}), "f");
__classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
__classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f");
__classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f");
}), "f");
// Don't let these promises cause unhandled rejection errors.
// we will manually cause an unhandled rejection error later
// if the user hasn't registered any error listener or called
// any promise-returning method.
__classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { });
__classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { });
__classPrivateFieldSet(this, _MessageStream_params, params, "f");
__classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f");
}
get response() {
return __classPrivateFieldGet(this, _MessageStream_response, "f");
}
get request_id() {
return __classPrivateFieldGet(this, _MessageStream_request_id, "f");
}
/**
* Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
* returned vie the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* This is the same as the `APIPromise.withResponse()` method.
*
* This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
* as no `Response` is available.
*/
async withResponse() {
__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f");
if (!response) {
throw new Error('Could not resolve a `Response` object');
}
return {
data: this,
response,
request_id: response.headers.get('request-id'),
};
}
/**
* Intended for use on the frontend, consuming a stream produced with
* `.toReadableStream()` on the backend.
*
* Note that messages sent to the model do not appear in `.on('message')`
* in this context.
*/
static fromReadableStream(stream) {
const runner = new MessageStream(null);
runner._run(() => runner._fromReadableStream(stream));
return runner;
}
static createMessage(messages, params, options, { logger } = {}) {
const runner = new MessageStream(params, { logger });
for (const message of params.messages) {
runner._addMessageParam(message);
}
__classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f");
runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));
return runner;
}
_run(executor) {
executor().then(() => {
this._emitFinal();
this._emit('end');
}, __classPrivateFieldGet(this, _MessageStream_handleError, "f"));
}
_addMessageParam(message) {
this.messages.push(message);
}
_addMessage(message, emit = true) {
this.receivedMessages.push(message);
if (emit) {
this._emit('message', message);
}
}
async _createMessage(messages, params, options) {
const signal = options?.signal;
let abortHandler;
if (signal) {
if (signal.aborted)
this.controller.abort();
abortHandler = this.controller.abort.bind(this.controller);
signal.addEventListener('abort', abortHandler);
}
try {
__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
const { response, data: stream } = await messages
.create({ ...params, stream: true }, { ...options, signal: this.controller.signal })
.withResponse();
this._connected(response);
for await (const event of stream) {
__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
}
finally {
if (signal && abortHandler) {
signal.removeEventListener('abort', abortHandler);
}
}
}
_connected(response) {
if (this.ended)
return;
__classPrivateFieldSet(this, _MessageStream_response, response, "f");
__classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f");
__classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
this._emit('connect');
}
get ended() {
return __classPrivateFieldGet(this, _MessageStream_ended, "f");
}
get errored() {
return __classPrivateFieldGet(this, _MessageStream_errored, "f");
}
get aborted() {
return __classPrivateFieldGet(this, _MessageStream_aborted, "f");
}
abort() {
this.controller.abort();
}
/**
* Adds the listener function to the end of the listeners array for the event.
* No checks are made to see if the listener has already been added. Multiple calls passing
* the same combination of event and listener will result in the listener being added, and
* called, multiple times.
* @returns this MessageStream, so that calls can be chained
*/
on(event, listener) {
const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
listeners.push({ listener });
return this;
}
/**
* Removes the specified listener from the listener array for the event.
* off() will remove, at most, one instance of a listener from the listener array. If any single
* listener has been added multiple times to the listener array for the specified event, then
* off() must be called multiple times to remove each instance.
* @returns this MessageStream, so that calls can be chained
*/
off(event, listener) {
const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
if (!listeners)
return this;
const index = listeners.findIndex((l) => l.listener === listener);
if (index >= 0)
listeners.splice(index, 1);
return this;
}
/**
* Adds a one-time listener function for the event. The next time the event is triggered,
* this listener is removed and then invoked.
* @returns this MessageStream, so that calls can be chained
*/
once(event, listener) {
const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []);
listeners.push({ listener, once: true });
return this;
}
/**
* This is similar to `.once()`, but returns a Promise that resolves the next time
* the event is triggered, instead of calling a listener callback.
* @returns a Promise that resolves the next time given event is triggered,
* or rejects if an error is emitted. (If you request the 'error' event,
* returns a promise that resolves with the error).
*
* Example:
*
* const message = await stream.emitted('message') // rejects if the stream errors
*/
emitted(event) {
return new Promise((resolve, reject) => {
__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
if (event !== 'error')
this.once('error', reject);
this.once(event, resolve);
});
}
async done() {
__classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f");
await __classPrivateFieldGet(this, _MessageStream_endPromise, "f");
}
get currentMessage() {
return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
}
/**
* @returns a promise that resolves with the the final assistant Message response,
* or rejects if an error occurred or the stream ended prematurely without producing a Message.
* If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field.
*/
async finalMessage() {
await this.done();
return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
}
/**
* @returns a promise that resolves with the the final assistant Message's text response, concatenated
* together if there are more than one text blocks.
* Rejects if an error occurred or the stream ended prematurely without producing a Message.
*/
async finalText() {
await this.done();
return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
}
_emit(event, ...args) {
// make sure we don't emit any MessageStreamEvents after end
if (__classPrivateFieldGet(this, _MessageStream_ended, "f"))
return;
if (event === 'end') {
__classPrivateFieldSet(this, _MessageStream_ended, true, "f");
__classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this);
}
const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event];
if (listeners) {
__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
listeners.forEach(({ listener }) => listener(...args));
}
if (event === 'abort') {
const error = args[0];
if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
Promise.reject(error);
}
__classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
this._emit('end');
return;
}
if (event === 'error') {
// NOTE: _emit('error', error) should only be called from #handleError().
const error = args[0];
if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
// Trigger an unhandled rejection if the user hasn't registered any error handlers.
// If you are seeing stack traces here, make sure to handle errors via either:
// - runner.on('error', () => ...)
// - await runner.done()
// - await runner.final...()
// - etc.
Promise.reject(error);
}
__classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
__classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error);
this._emit('end');
}
}
_emitFinal() {
const finalMessage = this.receivedMessages.at(-1);
if (finalMessage) {
this._emit('finalMessage', __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
}
}
async _fromReadableStream(readableStream, options) {
const signal = options?.signal;
let abortHandler;
if (signal) {
if (signal.aborted)
this.controller.abort();
abortHandler = this.controller.abort.bind(this.controller);
signal.addEventListener('abort', abortHandler);
}
try {
__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
this._connected(null);
const stream = Stream.fromReadableStream(readableStream, this.controller);
for await (const event of stream) {
__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
}
if (stream.controller.signal?.aborted) {
throw new APIUserAbortError();
}
__classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
}
finally {
if (signal && abortHandler) {
signal.removeEventListener('abort', abortHandler);
}
}
}
[(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_params = 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_logger = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() {
if (this.receivedMessages.length === 0) {
throw new AnthropicError('stream ended without producing a Message with role=assistant');
}
return this.receivedMessages.at(-1);
}, _MessageStream_getFinalText = function _MessageStream_getFinalText() {
if (this.receivedMessages.length === 0) {
throw new AnthropicError('stream ended without producing a Message with role=assistant');
}
const textBlocks = this.receivedMessages
.at(-1)
.content.filter((block) => block.type === 'text')
.map((block) => block.text);
if (textBlocks.length === 0) {
throw new AnthropicError('stream ended without producing a content block with type=text');
}
return textBlocks.join(' ');
}, _MessageStream_beginRequest = function _MessageStream_beginRequest() {
if (this.ended)
return;
__classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f");
}, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) {
if (this.ended)
return;
const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
this._emit('streamEvent', event, messageSnapshot);
switch (event.type) {
case 'content_block_delta': {
const content = messageSnapshot.content.at(-1);
switch (event.delta.type) {
case 'text_delta': {
if (content.type === 'text') {
this._emit('text', event.delta.text, content.text || '');
}
break;
}
case 'citations_delta': {
if (content.type === 'text') {
this._emit('citation', event.delta.citation, content.citations ?? []);
}
break;
}
case 'input_json_delta': {
if (tracksToolInput(content) && content.input) {
this._emit('inputJson', event.delta.partial_json, content.input);
}
break;
}
case 'thinking_delta': {
if (content.type === 'thinking') {
this._emit('thinking', event.delta.thinking, content.thinking);
}
break;
}
case 'signature_delta': {
if (content.type === 'thinking') {
this._emit('signature', content.signature);
}
break;
}
default:
checkNever(event.delta);
}
break;
}
case 'message_stop': {
this._addMessageParam(messageSnapshot);
this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true);
break;
}
case 'content_block_stop': {
this._emit('contentBlock', messageSnapshot.content.at(-1));
break;
}
case 'message_start': {
__classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
break;
}
case 'content_block_start':
case 'message_delta':
break;
}
}, _MessageStream_endRequest = function _MessageStream_endRequest() {
if (this.ended) {
throw new AnthropicError(`stream has ended, this shouldn't happen`);
}
const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
if (!snapshot) {
throw new AnthropicError(`request ended without sending any chunks`);
}
__classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f");
return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") });
}, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) {
let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f");
if (event.type === 'message_start') {
if (snapshot) {
throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
}
return event.message;
}
if (!snapshot) {
throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
}
switch (event.type) {
case 'message_stop':
return snapshot;
case 'message_delta':
snapshot.stop_reason = event.delta.stop_reason;
snapshot.stop_sequence = event.delta.stop_sequence;
snapshot.usage.output_tokens = event.usage.output_tokens;
// Update other usage fields if they exist in the event
if (event.usage.input_tokens != null) {
snapshot.usage.input_tokens = event.usage.input_tokens;
}
if (event.usage.cache_creation_input_tokens != null) {
snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
}
if (event.usage.cache_read_input_tokens != null) {
snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
}
if (event.usage.server_tool_use != null) {
snapshot.usage.server_tool_use = event.usage.server_tool_use;
}
return snapshot;
case 'content_block_start':
snapshot.content.push({ ...event.content_block });
return snapshot;
case 'content_block_delta': {
const snapshotContent = snapshot.content.at(event.index);
switch (event.delta.type) {
case 'text_delta': {
if (snapshotContent?.type === 'text') {
snapshot.content[event.index] = {
...snapshotContent,
text: (snapshotContent.text || '') + event.delta.text,
};
}
break;
}
case 'citations_delta': {
if (snapshotContent?.type === 'text') {
snapshot.content[event.index] = {
...snapshotContent,
citations: [...(snapshotContent.citations ?? []), event.delta.citation],
};
}
break;
}
case 'input_json_delta': {
if (snapshotContent && tracksToolInput(snapshotContent)) {
// we need to keep track of the raw JSON string as well so that we can
// re-parse it for each delta, for now we just store it as an untyped
// non-enumerable property on the snapshot
let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || '';
jsonBuf += event.delta.partial_json;
const newContent = { ...snapshotContent };
Object.defineProperty(newContent, JSON_BUF_PROPERTY, {
value: jsonBuf,
enumerable: false,
writable: true,
});
if (jsonBuf) {
newContent.input = partialParse(jsonBuf);
}
snapshot.content[event.index] = newContent;
}
break;
}
case 'thinking_delta': {
if (snapshotContent?.type === 'thinking') {
snapshot.content[event.index] = {
...snapshotContent,
thinking: snapshotContent.thinking + event.delta.thinking,
};
}
break;
}
case 'signature_delta': {
if (snapshotContent?.type === 'thinking') {
snapshot.content[event.index] = {
...snapshotContent,
signature: event.delta.signature,
};
}
break;
}
default:
checkNever(event.delta);
}
return snapshot;
}
case 'content_block_stop':
return snapshot;
}
}, Symbol.asyncIterator)]() {
const pushQueue = [];
const readQueue = [];
let done = false;
this.on('streamEvent', (event) => {
const reader = readQueue.shift();
if (reader) {
reader.resolve(event);
}
else {
pushQueue.push(event);
}
});
this.on('end', () => {
done = true;
for (const reader of readQueue) {
reader.resolve(undefined);
}
readQueue.length = 0;
});
this.on('abort', (err) => {
done = true;
for (const reader of readQueue) {
reader.reject(err);
}
readQueue.length = 0;
});
this.on('error', (err) => {
done = true;
for (const reader of readQueue) {
reader.reject(err);
}
readQueue.length = 0;
});
return {
next: async () => {
if (!pushQueue.length) {
if (done) {
return { value: undefined, done: true };
}
return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));
}
const chunk = pushQueue.shift();
return { value: chunk, done: false };
},
return: async () => {
this.abort();
return { value: undefined, done: true };
},
};
}
toReadableStream() {
const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
return stream.toReadableStream();
}
}
// used to ensure exhaustive case matching without throwing a runtime error
function checkNever(x) { }
//# sourceMappingURL=MessageStream.mjs.map

View File

@@ -0,0 +1,75 @@
import { AnthropicError } from "../core/error.mjs";
function getOutputFormat(params) {
// Prefer output_format (deprecated) over output_config.format for backward compatibility
return params?.output_format ?? params?.output_config?.format;
}
export function maybeParseBetaMessage(message, params, opts) {
const outputFormat = getOutputFormat(params);
if (!params || !('parse' in (outputFormat ?? {}))) {
return {
...message,
content: message.content.map((block) => {
if (block.type === 'text') {
const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
value: null,
enumerable: false,
});
return Object.defineProperty(parsedBlock, 'parsed', {
get() {
opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.');
return null;
},
enumerable: false,
});
}
return block;
}),
parsed_output: null,
};
}
return parseBetaMessage(message, params, opts);
}
export function parseBetaMessage(message, params, opts) {
let firstParsedOutput = null;
const content = message.content.map((block) => {
if (block.type === 'text') {
const parsedOutput = parseBetaOutputFormat(params, block.text);
if (firstParsedOutput === null) {
firstParsedOutput = parsedOutput;
}
const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
value: parsedOutput,
enumerable: false,
});
return Object.defineProperty(parsedBlock, 'parsed', {
get() {
opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.');
return parsedOutput;
},
enumerable: false,
});
}
return block;
});
return {
...message,
content,
parsed_output: firstParsedOutput,
};
}
function parseBetaOutputFormat(params, content) {
const outputFormat = getOutputFormat(params);
if (outputFormat?.type !== 'json_schema') {
return null;
}
try {
if ('parse' in outputFormat) {
return outputFormat.parse(content);
}
return JSON.parse(content);
}
catch (error) {
throw new AnthropicError(`Failed to parse structured output: ${error}`);
}
}
//# sourceMappingURL=beta-parser.mjs.map

View File

@@ -0,0 +1,62 @@
import { AnthropicError } from "../core/error.mjs";
function getOutputFormat(params) {
return params?.output_config?.format;
}
export function maybeParseMessage(message, params, opts) {
const outputFormat = getOutputFormat(params);
if (!params || !('parse' in (outputFormat ?? {}))) {
return {
...message,
content: message.content.map((block) => {
if (block.type === 'text') {
const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
value: null,
enumerable: false,
});
return parsedBlock;
}
return block;
}),
parsed_output: null,
};
}
return parseMessage(message, params, opts);
}
export function parseMessage(message, params, opts) {
let firstParsedOutput = null;
const content = message.content.map((block) => {
if (block.type === 'text') {
const parsedOutput = parseOutputFormat(params, block.text);
if (firstParsedOutput === null) {
firstParsedOutput = parsedOutput;
}
const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', {
value: parsedOutput,
enumerable: false,
});
return parsedBlock;
}
return block;
});
return {
...message,
content,
parsed_output: firstParsedOutput,
};
}
function parseOutputFormat(params, content) {
const outputFormat = getOutputFormat(params);
if (outputFormat?.type !== 'json_schema') {
return null;
}
try {
if ('parse' in outputFormat) {
return outputFormat.parse(content);
}
return JSON.parse(content);
}
catch (error) {
throw new AnthropicError(`Failed to parse structured output: ${error}`);
}
}
//# sourceMappingURL=parser.mjs.map

View File

@@ -0,0 +1,63 @@
/**
* Shared utilities for tracking SDK helper usage.
*/
/**
* Symbol used to mark objects created by SDK helpers for tracking.
* The value is the helper name (e.g., 'mcpTool', 'betaZodTool').
*/
export const SDK_HELPER_SYMBOL = Symbol('anthropic.sdk.stainlessHelper');
export function wasCreatedByStainlessHelper(value) {
return typeof value === 'object' && value !== null && SDK_HELPER_SYMBOL in value;
}
/**
* Collects helper names from tools and messages arrays.
* Returns a deduplicated array of helper names found.
*/
export function collectStainlessHelpers(tools, messages) {
const helpers = new Set();
// Collect from tools
if (tools) {
for (const tool of tools) {
if (wasCreatedByStainlessHelper(tool)) {
helpers.add(tool[SDK_HELPER_SYMBOL]);
}
}
}
// Collect from messages and their content blocks
if (messages) {
for (const message of messages) {
if (wasCreatedByStainlessHelper(message)) {
helpers.add(message[SDK_HELPER_SYMBOL]);
}
if (Array.isArray(message.content)) {
for (const block of message.content) {
if (wasCreatedByStainlessHelper(block)) {
helpers.add(block[SDK_HELPER_SYMBOL]);
}
}
}
}
}
return Array.from(helpers);
}
/**
* Builds x-stainless-helper header value from tools and messages.
* Returns an empty object if no helpers are found.
*/
export function stainlessHelperHeader(tools, messages) {
const helpers = collectStainlessHelpers(tools, messages);
if (helpers.length === 0)
return {};
return { 'x-stainless-helper': helpers.join(', ') };
}
/**
* Builds x-stainless-helper header value from a file object.
* Returns an empty object if the file is not marked with a helper.
*/
export function stainlessHelperHeaderFromFile(file) {
if (wasCreatedByStainlessHelper(file)) {
return { 'x-stainless-helper': file[SDK_HELPER_SYMBOL] };
}
return {};
}
//# sourceMappingURL=stainless-helper-header.mjs.map

View File

@@ -0,0 +1,372 @@
var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../../internal/tslib.mjs";
import { ToolError } from "./ToolError.mjs";
import { AnthropicError } from "../../core/error.mjs";
import { buildHeaders } from "../../internal/headers.mjs";
import { DEFAULT_SUMMARY_PROMPT, DEFAULT_TOKEN_THRESHOLD } from "./CompactionControl.mjs";
import { collectStainlessHelpers } from "../stainless-helper-header.mjs";
/**
* Just Promise.withResolvers(), which is not available in all environments.
*/
function promiseWithResolvers() {
let resolve;
let reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve: resolve, reject: reject };
}
/**
* A ToolRunner handles the automatic conversation loop between the assistant and tools.
*
* A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects
* depending on the streaming configuration.
*/
export class BetaToolRunner {
constructor(client, params, options) {
_BetaToolRunner_instances.add(this);
this.client = client;
/** Whether the async iterator has been consumed */
_BetaToolRunner_consumed.set(this, false);
/** Whether parameters have been mutated since the last API call */
_BetaToolRunner_mutated.set(this, false);
/** Current state containing the request parameters */
_BetaToolRunner_state.set(this, void 0);
_BetaToolRunner_options.set(this, void 0);
/** Promise for the last message received from the assistant */
_BetaToolRunner_message.set(this, void 0);
/** Cached tool response to avoid redundant executions */
_BetaToolRunner_toolResponse.set(this, void 0);
/** Promise resolvers for waiting on completion */
_BetaToolRunner_completion.set(this, void 0);
/** Number of iterations (API requests) made so far */
_BetaToolRunner_iterationCount.set(this, 0);
__classPrivateFieldSet(this, _BetaToolRunner_state, {
params: {
// You can't clone the entire params since there are functions as handlers.
// You also don't really need to clone params.messages, but it probably will prevent a foot gun
// somewhere.
...params,
messages: structuredClone(params.messages),
},
}, "f");
const helpers = collectStainlessHelpers(params.tools, params.messages);
const helperValue = ['BetaToolRunner', ...helpers].join(', ');
__classPrivateFieldSet(this, _BetaToolRunner_options, {
...options,
headers: buildHeaders([{ 'x-stainless-helper': helperValue }, options?.headers]),
}, "f");
__classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
}
async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() {
const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl;
if (!compactionControl || !compactionControl.enabled) {
return false;
}
let tokensUsed = 0;
if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) {
try {
const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f");
const totalInputTokens = message.usage.input_tokens +
(message.usage.cache_creation_input_tokens ?? 0) +
(message.usage.cache_read_input_tokens ?? 0);
tokensUsed = totalInputTokens + message.usage.output_tokens;
}
catch {
// If we can't get the message, skip compaction
return false;
}
}
const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD;
if (tokensUsed < threshold) {
return false;
}
const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model;
const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT;
const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages;
if (messages[messages.length - 1].role === 'assistant') {
// Remove tool_use blocks from the last message to avoid 400 error
// (tool_use requires tool_result, which we don't have yet)
const lastMessage = messages[messages.length - 1];
if (Array.isArray(lastMessage.content)) {
const nonToolBlocks = lastMessage.content.filter((block) => block.type !== 'tool_use');
if (nonToolBlocks.length === 0) {
// If all blocks were tool_use, just remove the message entirely
messages.pop();
}
else {
lastMessage.content = nonToolBlocks;
}
}
}
const response = await this.client.beta.messages.create({
model,
messages: [
...messages,
{
role: 'user',
content: [
{
type: 'text',
text: summaryPrompt,
},
],
},
],
max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens,
}, {
headers: { 'x-stainless-helper': 'compaction' },
});
if (response.content[0]?.type !== 'text') {
throw new AnthropicError('Expected text response for compaction');
}
__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [
{
role: 'user',
content: response.content,
},
];
return true;
}, Symbol.asyncIterator)]() {
var _a;
if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) {
throw new AnthropicError('Cannot iterate over a consumed stream');
}
__classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f");
__classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f");
__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f");
try {
while (true) {
let stream;
try {
if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations &&
__classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) {
break;
}
__classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f");
__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f");
__classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f");
__classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f");
const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params;
if (params.stream) {
stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f"));
__classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f");
// Make sure that this promise doesn't throw before we get the option to do something about it.
// Error will be caught when we call await this.#message ultimately
__classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => { });
yield stream;
}
else {
__classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f");
yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f");
}
const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this);
if (!isCompacted) {
if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) {
const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f");
__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content });
}
const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1));
if (toolMessage) {
__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage);
}
else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) {
break;
}
}
}
finally {
if (stream) {
stream.abort();
}
}
}
if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) {
throw new AnthropicError('ToolRunner concluded without a message from the server');
}
__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"));
}
catch (error) {
__classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f");
// Silence unhandled promise errors
__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { });
__classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error);
__classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
throw error;
}
}
setMessagesParams(paramsOrMutator) {
if (typeof paramsOrMutator === 'function') {
__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params);
}
else {
__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator;
}
__classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f");
// Invalidate cached tool response since parameters changed
__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f");
}
/**
* Get the tool response for the last message from the assistant.
* Avoids redundant tool executions by caching results.
*
* @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed
*
* @example
* const toolResponse = await runner.generateToolResponse();
* if (toolResponse) {
* console.log('Tool results:', toolResponse.content);
* }
*/
async generateToolResponse() {
const message = (await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")) ?? this.params.messages.at(-1);
if (!message) {
return null;
}
return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message);
}
/**
* Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and
* will wait for an instance to start and go to completion.
*
* @returns A promise that resolves to the final BetaMessage when the iterator completes
*
* @example
* // Start consuming the iterator
* for await (const message of runner) {
* console.log('Message:', message.content);
* }
*
* // Meanwhile, wait for completion from another part of the code
* const finalMessage = await runner.done();
* console.log('Final response:', finalMessage.content);
*/
done() {
return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise;
}
/**
* Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:
* * If the iterator has not been consumed, consume the entire iterator and return the final message from the
* assistant.
* * If the iterator has been consumed, waits for it to complete and returns the final message.
*
* @returns A promise that resolves to the final BetaMessage from the conversation
* @throws {AnthropicError} If no messages were processed during the conversation
*
* @example
* const finalMessage = await runner.runUntilDone();
* console.log('Final response:', finalMessage.content);
*/
async runUntilDone() {
// If not yet consumed, start consuming and wait for completion
if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) {
for await (const _ of this) {
// Iterator naturally populates this.#message
}
}
// If consumed but not completed, wait for completion
return this.done();
}
/**
* Get the current parameters being used by the ToolRunner.
*
* @returns A readonly view of the current ToolRunnerParams
*
* @example
* const currentParams = runner.params;
* console.log('Current model:', currentParams.model);
* console.log('Message count:', currentParams.messages.length);
*/
get params() {
return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params;
}
/**
* Add one or more messages to the conversation history.
*
* @param messages - One or more BetaMessageParam objects to add to the conversation
*
* @example
* runner.pushMessages(
* { role: 'user', content: 'Also, what about the weather in NYC?' }
* );
*
* @example
* // Adding multiple messages
* runner.pushMessages(
* { role: 'user', content: 'What about NYC?' },
* { role: 'user', content: 'And Boston?' }
* );
*/
pushMessages(...messages) {
this.setMessagesParams((params) => ({
...params,
messages: [...params.messages, ...messages],
}));
}
/**
* Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()
* This allows using `await runner` instead of `await runner.runUntilDone()`
*/
then(onfulfilled, onrejected) {
return this.runUntilDone().then(onfulfilled, onrejected);
}
}
_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) {
if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) {
return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f");
}
__classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f");
return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f");
};
async function generateToolResponse(params, lastMessage = params.messages.at(-1)) {
// Only process if the last message is from the assistant and has tool use blocks
if (!lastMessage ||
lastMessage.role !== 'assistant' ||
!lastMessage.content ||
typeof lastMessage.content === 'string') {
return null;
}
const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use');
if (toolUseBlocks.length === 0) {
return null;
}
const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => {
const tool = params.tools.find((t) => ('name' in t ? t.name : t.mcp_server_name) === toolUse.name);
if (!tool || !('run' in tool)) {
return {
type: 'tool_result',
tool_use_id: toolUse.id,
content: `Error: Tool '${toolUse.name}' not found`,
is_error: true,
};
}
try {
let input = toolUse.input;
if ('parse' in tool && tool.parse) {
input = tool.parse(input);
}
const result = await tool.run(input);
return {
type: 'tool_result',
tool_use_id: toolUse.id,
content: result,
};
}
catch (error) {
return {
type: 'tool_result',
tool_use_id: toolUse.id,
content: error instanceof ToolError ?
error.content
: `Error: ${error instanceof Error ? error.message : String(error)}`,
is_error: true,
};
}
}));
return {
role: 'user',
content: toolResults,
};
}
//# sourceMappingURL=BetaToolRunner.mjs.map

View File

@@ -0,0 +1,25 @@
export const DEFAULT_TOKEN_THRESHOLD = 100000;
export const DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;
//# sourceMappingURL=CompactionControl.mjs.map

View File

@@ -0,0 +1,38 @@
/**
* An error that can be thrown from a tool's `run` method to return structured
* content blocks as the error result, rather than just a string message.
*
* When the ToolRunner catches this error, it will use the `content` property
* as the tool result with `is_error: true`.
*
* @example
* ```ts
* const tool = {
* name: 'my_tool',
* run: async (input) => {
* if (somethingWentWrong) {
* throw new ToolError([
* { type: 'text', text: 'Error details here' },
* { type: 'image', source: { type: 'base64', data: '...', media_type: 'image/png' } },
* ]);
* }
* return 'success';
* },
* };
* ```
*/
export class ToolError extends Error {
constructor(content) {
const message = typeof content === 'string' ? content : (content
.map((block) => {
if (block.type === 'text')
return block.text;
return `[${block.type}]`;
})
.join(' '));
super(message);
this.name = 'ToolError';
this.content = content;
}
}
//# sourceMappingURL=ToolError.mjs.map

View File

@@ -0,0 +1,24 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
import * as FilesAPI from "./files.mjs";
import { Files, } from "./files.mjs";
import * as ModelsAPI from "./models.mjs";
import { Models } from "./models.mjs";
import * as MessagesAPI from "./messages/messages.mjs";
import { Messages, } from "./messages/messages.mjs";
import * as SkillsAPI from "./skills/skills.mjs";
import { Skills, } from "./skills/skills.mjs";
export class Beta extends APIResource {
constructor() {
super(...arguments);
this.models = new ModelsAPI.Models(this._client);
this.messages = new MessagesAPI.Messages(this._client);
this.files = new FilesAPI.Files(this._client);
this.skills = new SkillsAPI.Skills(this._client);
}
}
Beta.Models = Models;
Beta.Messages = Messages;
Beta.Files = Files;
Beta.Skills = Skills;
//# sourceMappingURL=beta.mjs.map

View File

@@ -0,0 +1,120 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
import { Page } from "../../core/pagination.mjs";
import { buildHeaders } from "../../internal/headers.mjs";
import { stainlessHelperHeaderFromFile } from "../../lib/stainless-helper-header.mjs";
import { multipartFormRequestOptions } from "../../internal/uploads.mjs";
import { path } from "../../internal/utils/path.mjs";
export class Files extends APIResource {
/**
* List Files
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const fileMetadata of client.beta.files.list()) {
* // ...
* }
* ```
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/files', (Page), {
query,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
options?.headers,
]),
});
}
/**
* Delete File
*
* @example
* ```ts
* const deletedFile = await client.beta.files.delete(
* 'file_id',
* );
* ```
*/
delete(fileID, params = {}, options) {
const { betas } = params ?? {};
return this._client.delete(path `/v1/files/${fileID}`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
options?.headers,
]),
});
}
/**
* Download File
*
* @example
* ```ts
* const response = await client.beta.files.download(
* 'file_id',
* );
*
* const content = await response.blob();
* console.log(content);
* ```
*/
download(fileID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/files/${fileID}/content`, {
...options,
headers: buildHeaders([
{
'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(),
Accept: 'application/binary',
},
options?.headers,
]),
__binaryResponse: true,
});
}
/**
* Get File Metadata
*
* @example
* ```ts
* const fileMetadata =
* await client.beta.files.retrieveMetadata('file_id');
* ```
*/
retrieveMetadata(fileID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/files/${fileID}`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
options?.headers,
]),
});
}
/**
* Upload File
*
* @example
* ```ts
* const fileMetadata = await client.beta.files.upload({
* file: fs.createReadStream('path/to/file'),
* });
* ```
*/
upload(params, options) {
const { betas, ...body } = params;
return this._client.post('/v1/files', multipartFormRequestOptions({
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() },
stainlessHelperHeaderFromFile(body.file),
options?.headers,
]),
}, this._client));
}
}
//# sourceMappingURL=files.mjs.map

View File

@@ -0,0 +1,200 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../../core/resource.mjs";
import { Page } from "../../../core/pagination.mjs";
import { buildHeaders } from "../../../internal/headers.mjs";
import { JSONLDecoder } from "../../../internal/decoders/jsonl.mjs";
import { AnthropicError } from "../../../error.mjs";
import { path } from "../../../internal/utils/path.mjs";
export class Batches extends APIResource {
/**
* Send a batch of Message creation requests.
*
* The Message Batches API can be used to process multiple Messages API requests at
* once. Once a Message Batch is created, it begins processing immediately. Batches
* can take up to 24 hours to complete.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.create({
* requests: [
* {
* custom_id: 'my-custom-id-1',
* params: {
* max_tokens: 1024,
* messages: [
* { content: 'Hello, world', role: 'user' },
* ],
* model: 'claude-opus-4-6',
* },
* },
* ],
* });
* ```
*/
create(params, options) {
const { betas, ...body } = params;
return this._client.post('/v1/messages/batches?beta=true', {
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* This endpoint is idempotent and can be used to poll for Message Batch
* completion. To access the results of a Message Batch, make a request to the
* `results_url` field in the response.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.retrieve(
* 'message_batch_id',
* );
* ```
*/
retrieve(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* List all Message Batches within a Workspace. Most recently created batches are
* returned first.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const betaMessageBatch of client.beta.messages.batches.list()) {
* // ...
* }
* ```
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), {
query,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Delete a Message Batch.
*
* Message Batches can only be deleted once they've finished processing. If you'd
* like to delete an in-progress batch, you must first cancel it.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaDeletedMessageBatch =
* await client.beta.messages.batches.delete(
* 'message_batch_id',
* );
* ```
*/
delete(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Batches may be canceled any time before processing ends. Once cancellation is
* initiated, the batch enters a `canceling` state, at which time the system may
* complete any in-progress, non-interruptible requests before finalizing
* cancellation.
*
* The number of canceled requests is specified in `request_counts`. To determine
* which requests were canceled, check the individual results within the batch.
* Note that cancellation may not result in any canceled requests if they were
* non-interruptible.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatch =
* await client.beta.messages.batches.cancel(
* 'message_batch_id',
* );
* ```
*/
cancel(messageBatchID, params = {}, options) {
const { betas } = params ?? {};
return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() },
options?.headers,
]),
});
}
/**
* Streams the results of a Message Batch as a `.jsonl` file.
*
* Each line in the file is a JSON object containing the result of a single request
* in the Message Batch. Results are not guaranteed to be in the same order as
* requests. Use the `custom_id` field to match results to requests.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* const betaMessageBatchIndividualResponse =
* await client.beta.messages.batches.results(
* 'message_batch_id',
* );
* ```
*/
async results(messageBatchID, params = {}, options) {
const batch = await this.retrieve(messageBatchID);
if (!batch.results_url) {
throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
}
const { betas } = params ?? {};
return this._client
.get(batch.results_url, {
...options,
headers: buildHeaders([
{
'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(),
Accept: 'application/binary',
},
options?.headers,
]),
stream: true,
__binaryResponse: true,
})
._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
}
}
//# sourceMappingURL=batches.mjs.map

View File

@@ -0,0 +1,156 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { AnthropicError } from "../../../error.mjs";
import { APIResource } from "../../../core/resource.mjs";
import { MODEL_NONSTREAMING_TOKENS } from "../../../internal/constants.mjs";
import { buildHeaders } from "../../../internal/headers.mjs";
import { stainlessHelperHeader } from "../../../lib/stainless-helper-header.mjs";
import { parseBetaMessage, } from "../../../lib/beta-parser.mjs";
import { BetaMessageStream } from "../../../lib/BetaMessageStream.mjs";
import { BetaToolRunner, } from "../../../lib/tools/BetaToolRunner.mjs";
import { ToolError } from "../../../lib/tools/ToolError.mjs";
import * as BatchesAPI from "./batches.mjs";
import { Batches, } from "./batches.mjs";
const DEPRECATED_MODELS = {
'claude-1.3': 'November 6th, 2024',
'claude-1.3-100k': 'November 6th, 2024',
'claude-instant-1.1': 'November 6th, 2024',
'claude-instant-1.1-100k': 'November 6th, 2024',
'claude-instant-1.2': 'November 6th, 2024',
'claude-3-sonnet-20240229': 'July 21st, 2025',
'claude-3-opus-20240229': 'January 5th, 2026',
'claude-2.1': 'July 21st, 2025',
'claude-2.0': 'July 21st, 2025',
'claude-3-7-sonnet-latest': 'February 19th, 2026',
'claude-3-7-sonnet-20250219': 'February 19th, 2026',
};
const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6'];
export class Messages extends APIResource {
constructor() {
super(...arguments);
this.batches = new BatchesAPI.Batches(this._client);
}
create(params, options) {
// Transform deprecated output_format to output_config.format
const modifiedParams = transformOutputFormat(params);
const { betas, ...body } = modifiedParams;
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.`);
}
if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&
body.thinking &&
body.thinking.type === 'enabled') {
console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
}
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);
}
// Collect helper info from tools and messages
const helperHeader = stainlessHelperHeader(body.tools, body.messages);
return this._client.post('/v1/messages?beta=true', {
body,
timeout: timeout ?? 600000,
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
helperHeader,
options?.headers,
]),
stream: modifiedParams.stream ?? false,
});
}
/**
* Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
* the response will be automatically parsed and available in the `parsed_output` property of the message.
*
* @example
* ```ts
* const message = await client.beta.messages.parse({
* model: 'claude-3-5-sonnet-20241022',
* max_tokens: 1024,
* messages: [{ role: 'user', content: 'What is 2+2?' }],
* output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
* });
*
* console.log(message.parsed_output?.answer); // 4
* ```
*/
parse(params, options) {
options = {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-12-15'].toString() },
options?.headers,
]),
};
return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console }));
}
/**
* Create a Message stream
*/
stream(body, options) {
return BetaMessageStream.createMessage(this, body, options);
}
/**
* Count the number of tokens in a Message.
*
* The Token Count API can be used to count the number of tokens in a Message,
* including tools, images, and documents, without creating it.
*
* Learn more about token counting in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
*
* @example
* ```ts
* const betaMessageTokensCount =
* await client.beta.messages.countTokens({
* messages: [{ content: 'string', role: 'user' }],
* model: 'claude-opus-4-6',
* });
* ```
*/
countTokens(params, options) {
// Transform deprecated output_format to output_config.format
const modifiedParams = transformOutputFormat(params);
const { betas, ...body } = modifiedParams;
return this._client.post('/v1/messages/count_tokens?beta=true', {
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() },
options?.headers,
]),
});
}
toolRunner(body, options) {
return new BetaToolRunner(this._client, body, options);
}
}
/**
* Transform deprecated output_format to output_config.format
* Returns a modified copy of the params without mutating the original
*/
function transformOutputFormat(params) {
if (!params.output_format) {
return params;
}
if (params.output_config?.format) {
throw new AnthropicError('Both output_format and output_config.format were provided. ' +
'Please use only output_config.format (output_format is deprecated).');
}
const { output_format, ...rest } = params;
return {
...rest,
output_config: {
...params.output_config,
format: output_format,
},
};
}
export { BetaToolRunner } from "../../../lib/tools/BetaToolRunner.mjs";
export { ToolError } from "../../../lib/tools/ToolError.mjs";
Messages.Batches = Batches;
Messages.BetaToolRunner = BetaToolRunner;
Messages.ToolError = ToolError;
//# sourceMappingURL=messages.mjs.map

View File

@@ -0,0 +1,56 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
import { Page } from "../../core/pagination.mjs";
import { buildHeaders } from "../../internal/headers.mjs";
import { path } from "../../internal/utils/path.mjs";
export class Models extends APIResource {
/**
* Get a specific model.
*
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
*
* @example
* ```ts
* const betaModelInfo = await client.beta.models.retrieve(
* 'model_id',
* );
* ```
*/
retrieve(modelID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/models/${modelID}?beta=true`, {
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
options?.headers,
]),
});
}
/**
* List available models.
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const betaModelInfo of client.beta.models.list()) {
* // ...
* }
* ```
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/models?beta=true', (Page), {
query,
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
options?.headers,
]),
});
}
}
//# sourceMappingURL=models.mjs.map

View File

@@ -0,0 +1,93 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../../core/resource.mjs";
import * as VersionsAPI from "./versions.mjs";
import { Versions, } from "./versions.mjs";
import { PageCursor } from "../../../core/pagination.mjs";
import { buildHeaders } from "../../../internal/headers.mjs";
import { multipartFormRequestOptions } from "../../../internal/uploads.mjs";
import { path } from "../../../internal/utils/path.mjs";
export class Skills extends APIResource {
constructor() {
super(...arguments);
this.versions = new VersionsAPI.Versions(this._client);
}
/**
* Create Skill
*
* @example
* ```ts
* const skill = await client.beta.skills.create();
* ```
*/
create(params = {}, options) {
const { betas, ...body } = params ?? {};
return this._client.post('/v1/skills?beta=true', multipartFormRequestOptions({
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
}, this._client, false));
}
/**
* Get Skill
*
* @example
* ```ts
* const skill = await client.beta.skills.retrieve('skill_id');
* ```
*/
retrieve(skillID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/skills/${skillID}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
});
}
/**
* List Skills
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const skillListResponse of client.beta.skills.list()) {
* // ...
* }
* ```
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/skills?beta=true', (PageCursor), {
query,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
});
}
/**
* Delete Skill
*
* @example
* ```ts
* const skill = await client.beta.skills.delete('skill_id');
* ```
*/
delete(skillID, params = {}, options) {
const { betas } = params ?? {};
return this._client.delete(path `/v1/skills/${skillID}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
});
}
}
Skills.Versions = Versions;
//# sourceMappingURL=skills.mjs.map

View File

@@ -0,0 +1,96 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../../core/resource.mjs";
import { PageCursor } from "../../../core/pagination.mjs";
import { buildHeaders } from "../../../internal/headers.mjs";
import { multipartFormRequestOptions } from "../../../internal/uploads.mjs";
import { path } from "../../../internal/utils/path.mjs";
export class Versions extends APIResource {
/**
* Create Skill Version
*
* @example
* ```ts
* const version = await client.beta.skills.versions.create(
* 'skill_id',
* );
* ```
*/
create(skillID, params = {}, options) {
const { betas, ...body } = params ?? {};
return this._client.post(path `/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({
body,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
}, this._client));
}
/**
* Get Skill Version
*
* @example
* ```ts
* const version = await client.beta.skills.versions.retrieve(
* 'version',
* { skill_id: 'skill_id' },
* );
* ```
*/
retrieve(version, params, options) {
const { skill_id, betas } = params;
return this._client.get(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
});
}
/**
* List Skill Versions
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const versionListResponse of client.beta.skills.versions.list(
* 'skill_id',
* )) {
* // ...
* }
* ```
*/
list(skillID, params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList(path `/v1/skills/${skillID}/versions?beta=true`, (PageCursor), {
query,
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
});
}
/**
* Delete Skill Version
*
* @example
* ```ts
* const version = await client.beta.skills.versions.delete(
* 'version',
* { skill_id: 'skill_id' },
* );
* ```
*/
delete(version, params, options) {
const { skill_id, betas } = params;
return this._client.delete(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, {
...options,
headers: buildHeaders([
{ 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() },
options?.headers,
]),
});
}
}
//# sourceMappingURL=versions.mjs.map

View File

@@ -0,0 +1,19 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../core/resource.mjs";
import { buildHeaders } from "../internal/headers.mjs";
export class Completions extends APIResource {
create(params, options) {
const { betas, ...body } = params;
return this._client.post('/v1/complete', {
body,
timeout: this._client._options.timeout ?? 600000,
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
options?.headers,
]),
stream: params.stream ?? false,
});
}
}
//# sourceMappingURL=completions.mjs.map

View File

@@ -0,0 +1,7 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export * from "./shared.mjs";
export { Beta, } from "./beta/beta.mjs";
export { Completions, } from "./completions.mjs";
export { Messages, } from "./messages/messages.mjs";
export { Models, } from "./models.mjs";
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1,149 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
import { Page } from "../../core/pagination.mjs";
import { buildHeaders } from "../../internal/headers.mjs";
import { JSONLDecoder } from "../../internal/decoders/jsonl.mjs";
import { AnthropicError } from "../../error.mjs";
import { path } from "../../internal/utils/path.mjs";
export class Batches extends APIResource {
/**
* Send a batch of Message creation requests.
*
* The Message Batches API can be used to process multiple Messages API requests at
* once. Once a Message Batch is created, it begins processing immediately. Batches
* can take up to 24 hours to complete.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/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-opus-4-6',
* },
* },
* ],
* });
* ```
*/
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](https://docs.claude.com/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](https://docs.claude.com/en/docs/build-with-claude/batch-processing)
*
* @example
* ```ts
* // Automatically fetches more pages as needed.
* for await (const messageBatch of client.messages.batches.list()) {
* // ...
* }
* ```
*/
list(query = {}, options) {
return this._client.getAPIList('/v1/messages/batches', (Page), { query, ...options });
}
/**
* Delete a Message Batch.
*
* Message Batches can only be deleted once they've finished processing. If you'd
* like to delete an in-progress batch, you must first cancel it.
*
* Learn more about the Message Batches API in our
* [user guide](https://docs.claude.com/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](https://docs.claude.com/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](https://docs.claude.com/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 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

View File

@@ -0,0 +1,123 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../../core/resource.mjs";
import { buildHeaders } from "../../internal/headers.mjs";
import { stainlessHelperHeader } from "../../lib/stainless-helper-header.mjs";
import { MessageStream } from "../../lib/MessageStream.mjs";
import { parseMessage, } from "../../lib/parser.mjs";
import * as BatchesAPI from "./batches.mjs";
import { Batches, } from "./batches.mjs";
import { MODEL_NONSTREAMING_TOKENS } from "../../internal/constants.mjs";
export class Messages extends APIResource {
constructor() {
super(...arguments);
this.batches = new BatchesAPI.Batches(this._client);
}
create(body, options) {
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.`);
}
if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED &&
body.thinking &&
body.thinking.type === 'enabled') {
console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
}
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);
}
// Collect helper info from tools and messages
const helperHeader = stainlessHelperHeader(body.tools, body.messages);
return this._client.post('/v1/messages', {
body,
timeout: timeout ?? 600000,
...options,
headers: buildHeaders([helperHeader, options?.headers]),
stream: body.stream ?? false,
});
}
/**
* Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and
* the response will be automatically parsed and available in the `parsed_output` property of the message.
*
* @example
* ```ts
* const message = await client.messages.parse({
* model: 'claude-sonnet-4-5-20250929',
* max_tokens: 1024,
* messages: [{ role: 'user', content: 'What is 2+2?' }],
* output_config: {
* format: zodOutputFormat(z.object({ answer: z.number() })),
* },
* });
*
* console.log(message.parsed_output?.answer); // 4
* ```
*/
parse(params, options) {
return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console }));
}
/**
* Create a Message stream.
*
* If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`),
* the final message will include a `parsed_output` property with the parsed content.
*
* @example
* ```ts
* const stream = client.messages.stream({
* model: 'claude-sonnet-4-5-20250929',
* max_tokens: 1024,
* messages: [{ role: 'user', content: 'What is 2+2?' }],
* output_config: {
* format: zodOutputFormat(z.object({ answer: z.number() })),
* },
* });
*
* const message = await stream.finalMessage();
* console.log(message.parsed_output?.answer); // 4
* ```
*/
stream(body, options) {
return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console });
}
/**
* Count the number of tokens in a Message.
*
* The Token Count API can be used to count the number of tokens in a Message,
* including tools, images, and documents, without creating it.
*
* Learn more about token counting in our
* [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting)
*
* @example
* ```ts
* const messageTokensCount =
* await client.messages.countTokens({
* messages: [{ content: 'string', role: 'user' }],
* model: 'claude-opus-4-6',
* });
* ```
*/
countTokens(body, options) {
return this._client.post('/v1/messages/count_tokens', { body, ...options });
}
}
const DEPRECATED_MODELS = {
'claude-1.3': 'November 6th, 2024',
'claude-1.3-100k': 'November 6th, 2024',
'claude-instant-1.1': 'November 6th, 2024',
'claude-instant-1.1-100k': 'November 6th, 2024',
'claude-instant-1.2': 'November 6th, 2024',
'claude-3-sonnet-20240229': 'July 21st, 2025',
'claude-3-opus-20240229': 'January 5th, 2026',
'claude-2.1': 'July 21st, 2025',
'claude-2.0': 'July 21st, 2025',
'claude-3-7-sonnet-latest': 'February 19th, 2026',
'claude-3-7-sonnet-20250219': 'February 19th, 2026',
'claude-3-5-haiku-latest': 'February 19th, 2026',
'claude-3-5-haiku-20241022': 'February 19th, 2026',
};
const MODELS_TO_WARN_WITH_THINKING_ENABLED = ['claude-opus-4-6'];
Messages.Batches = Batches;
//# sourceMappingURL=messages.mjs.map

View File

@@ -0,0 +1,41 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from "../core/resource.mjs";
import { Page } from "../core/pagination.mjs";
import { buildHeaders } from "../internal/headers.mjs";
import { path } from "../internal/utils/path.mjs";
export class Models extends APIResource {
/**
* Get a specific model.
*
* The Models API response can be used to determine information about a specific
* model or resolve a model alias to a model ID.
*/
retrieve(modelID, params = {}, options) {
const { betas } = params ?? {};
return this._client.get(path `/v1/models/${modelID}`, {
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
options?.headers,
]),
});
}
/**
* List available models.
*
* The Models API response can be used to determine which models are available for
* use in the API. More recently released models are listed first.
*/
list(params = {}, options) {
const { betas, ...query } = params ?? {};
return this._client.getAPIList('/v1/models', (Page), {
query,
...options,
headers: buildHeaders([
{ ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) },
options?.headers,
]),
});
}
}
//# sourceMappingURL=models.mjs.map

View File

@@ -0,0 +1,2 @@
export * from "./core/streaming.mjs";
//# sourceMappingURL=streaming.mjs.map

View File

@@ -0,0 +1,2 @@
export const VERSION = '0.74.0'; // x-release-please-version
//# sourceMappingURL=version.mjs.map

View File

@@ -0,0 +1,64 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveHttpAuthSchemeConfig = exports.defaultBedrockRuntimeHttpAuthSchemeProvider = exports.defaultBedrockRuntimeHttpAuthSchemeParametersProvider = void 0;
const core_1 = require("@aws-sdk/core");
const core_2 = require("@smithy/core");
const util_middleware_1 = require("@smithy/util-middleware");
const defaultBedrockRuntimeHttpAuthSchemeParametersProvider = async (config, context, input) => {
return {
operation: (0, util_middleware_1.getSmithyContext)(context).operation,
region: (await (0, util_middleware_1.normalizeProvider)(config.region)()) ||
(() => {
throw new Error("expected `region` to be configured for `aws.auth#sigv4`");
})(),
};
};
exports.defaultBedrockRuntimeHttpAuthSchemeParametersProvider = defaultBedrockRuntimeHttpAuthSchemeParametersProvider;
function createAwsAuthSigv4HttpAuthOption(authParameters) {
return {
schemeId: "aws.auth#sigv4",
signingProperties: {
name: "bedrock",
region: authParameters.region,
},
propertiesExtractor: (config, context) => ({
signingProperties: {
config,
context,
},
}),
};
}
function createSmithyApiHttpBearerAuthHttpAuthOption(authParameters) {
return {
schemeId: "smithy.api#httpBearerAuth",
propertiesExtractor: ({ profile, filepath, configFilepath, ignoreCache }, context) => ({
identityProperties: {
profile,
filepath,
configFilepath,
ignoreCache,
},
}),
};
}
const defaultBedrockRuntimeHttpAuthSchemeProvider = (authParameters) => {
const options = [];
switch (authParameters.operation) {
default: {
options.push(createAwsAuthSigv4HttpAuthOption(authParameters));
options.push(createSmithyApiHttpBearerAuthHttpAuthOption(authParameters));
}
}
return options;
};
exports.defaultBedrockRuntimeHttpAuthSchemeProvider = defaultBedrockRuntimeHttpAuthSchemeProvider;
const resolveHttpAuthSchemeConfig = (config) => {
const token = (0, core_2.memoizeIdentityProvider)(config.token, core_2.isIdentityExpired, core_2.doesIdentityRequireRefresh);
const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config);
return Object.assign(config_0, {
authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []),
token,
});
};
exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig;

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultEndpointResolver = void 0;
const util_endpoints_1 = require("@aws-sdk/util-endpoints");
const util_endpoints_2 = require("@smithy/util-endpoints");
const ruleset_1 = require("./ruleset");
const cache = new util_endpoints_2.EndpointCache({
size: 50,
params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"],
});
const defaultEndpointResolver = (endpointParams, context = {}) => {
return cache.get(endpointParams, () => (0, util_endpoints_2.resolveEndpoint)(ruleset_1.ruleSet, {
endpointParams: endpointParams,
logger: context.logger,
}));
};
exports.defaultEndpointResolver = defaultEndpointResolver;
util_endpoints_2.customEndpointFunctions.aws = util_endpoints_1.awsEndpointFunctions;

View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ruleSet = void 0;
const s = "required", t = "fn", u = "argv", v = "ref";
const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = { [s]: false, "type": "string" }, i = { [s]: true, "default": false, "type": "boolean" }, j = { [v]: "Endpoint" }, k = { [t]: c, [u]: [{ [v]: "UseFIPS" }, true] }, l = { [t]: c, [u]: [{ [v]: "UseDualStack" }, true] }, m = {}, n = { [t]: "getAttr", [u]: [{ [v]: g }, "supportsFIPS"] }, o = { [t]: c, [u]: [true, { [t]: "getAttr", [u]: [{ [v]: g }, "supportsDualStack"] }] }, p = [k], q = [l], r = [{ [v]: "Region" }];
const _data = { version: "1.0", parameters: { Region: h, UseDualStack: i, UseFIPS: i, Endpoint: h }, rules: [{ conditions: [{ [t]: b, [u]: [j] }], rules: [{ conditions: p, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: q, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: j, properties: m, headers: m }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [t]: b, [u]: r }], rules: [{ conditions: [{ [t]: "aws.partition", [u]: r, assign: g }], rules: [{ conditions: [k, l], rules: [{ conditions: [{ [t]: c, [u]: [a, n] }, o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: p, rules: [{ conditions: [{ [t]: c, [u]: [n, a] }], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: q, rules: [{ conditions: [o], rules: [{ rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { rules: [{ endpoint: { url: "https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}", properties: m, headers: m }, type: e }], type: f }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] };
exports.ruleSet = _data;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRuntimeConfig = void 0;
const tslib_1 = require("tslib");
const package_json_1 = tslib_1.__importDefault(require("../package.json"));
const core_1 = require("@aws-sdk/core");
const credential_provider_node_1 = require("@aws-sdk/credential-provider-node");
const eventstream_handler_node_1 = require("@aws-sdk/eventstream-handler-node");
const token_providers_1 = require("@aws-sdk/token-providers");
const util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node");
const config_resolver_1 = require("@smithy/config-resolver");
const core_2 = require("@smithy/core");
const eventstream_serde_node_1 = require("@smithy/eventstream-serde-node");
const hash_node_1 = require("@smithy/hash-node");
const middleware_retry_1 = require("@smithy/middleware-retry");
const node_config_provider_1 = require("@smithy/node-config-provider");
const node_http_handler_1 = require("@smithy/node-http-handler");
const util_body_length_node_1 = require("@smithy/util-body-length-node");
const util_retry_1 = require("@smithy/util-retry");
const runtimeConfig_shared_1 = require("./runtimeConfig.shared");
const smithy_client_1 = require("@smithy/smithy-client");
const util_defaults_mode_node_1 = require("@smithy/util-defaults-mode-node");
const smithy_client_2 = require("@smithy/smithy-client");
const getRuntimeConfig = (config) => {
(0, smithy_client_2.emitWarningIfUnsupportedVersion)(process.version);
const defaultsMode = (0, util_defaults_mode_node_1.resolveDefaultsModeConfig)(config);
const defaultConfigProvider = () => defaultsMode().then(smithy_client_1.loadConfigsForDefaultMode);
const clientSharedValues = (0, runtimeConfig_shared_1.getRuntimeConfig)(config);
(0, core_1.emitWarningIfUnsupportedVersion)(process.version);
const loaderConfig = {
profile: config?.profile,
logger: clientSharedValues.logger,
signingName: "bedrock",
};
return {
...clientSharedValues,
...config,
runtime: "node",
defaultsMode,
authSchemePreference: config?.authSchemePreference ?? (0, node_config_provider_1.loadConfig)(core_1.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig),
bodyLengthChecker: config?.bodyLengthChecker ?? util_body_length_node_1.calculateBodyLength,
credentialDefaultProvider: config?.credentialDefaultProvider ?? credential_provider_node_1.defaultProvider,
defaultUserAgentProvider: config?.defaultUserAgentProvider ??
(0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }),
eventStreamPayloadHandlerProvider: config?.eventStreamPayloadHandlerProvider ?? eventstream_handler_node_1.eventStreamPayloadHandlerProvider,
eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventstream_serde_node_1.eventStreamSerdeProvider,
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
signer: new core_1.AwsSdkSigV4Signer(),
},
{
schemeId: "smithy.api#httpBearerAuth",
identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth") ||
(async (idProps) => {
try {
return await (0, token_providers_1.fromEnvSigningName)({ signingName: "bedrock" })();
}
catch (error) {
return await (0, token_providers_1.nodeProvider)(idProps)(idProps);
}
}),
signer: new core_2.HttpBearerAuthSigner(),
},
],
maxAttempts: config?.maxAttempts ?? (0, node_config_provider_1.loadConfig)(middleware_retry_1.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config),
region: config?.region ??
(0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_REGION_CONFIG_OPTIONS, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }),
requestHandler: node_http_handler_1.NodeHttp2Handler.create(config?.requestHandler ?? (async () => ({ ...(await defaultConfigProvider()), disableConcurrentStreams: true }))),
retryMode: config?.retryMode ??
(0, node_config_provider_1.loadConfig)({
...middleware_retry_1.NODE_RETRY_MODE_CONFIG_OPTIONS,
default: async () => (await defaultConfigProvider()).retryMode || util_retry_1.DEFAULT_RETRY_MODE,
}, config),
sha256: config?.sha256 ?? hash_node_1.Hash.bind(null, "sha256"),
streamCollector: config?.streamCollector ?? node_http_handler_1.streamCollector,
useDualstackEndpoint: config?.useDualstackEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
useFipsEndpoint: config?.useFipsEndpoint ?? (0, node_config_provider_1.loadConfig)(config_resolver_1.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig),
userAgentAppId: config?.userAgentAppId ?? (0, node_config_provider_1.loadConfig)(util_user_agent_node_1.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig),
};
};
exports.getRuntimeConfig = getRuntimeConfig;

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRuntimeConfig = void 0;
const core_1 = require("@aws-sdk/core");
const protocols_1 = require("@aws-sdk/core/protocols");
const core_2 = require("@smithy/core");
const smithy_client_1 = require("@smithy/smithy-client");
const url_parser_1 = require("@smithy/url-parser");
const util_base64_1 = require("@smithy/util-base64");
const util_utf8_1 = require("@smithy/util-utf8");
const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider");
const endpointResolver_1 = require("./endpoint/endpointResolver");
const getRuntimeConfig = (config) => {
return {
apiVersion: "2023-09-30",
base64Decoder: config?.base64Decoder ?? util_base64_1.fromBase64,
base64Encoder: config?.base64Encoder ?? util_base64_1.toBase64,
disableHostPrefix: config?.disableHostPrefix ?? false,
endpointProvider: config?.endpointProvider ?? endpointResolver_1.defaultEndpointResolver,
extensions: config?.extensions ?? [],
httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? httpAuthSchemeProvider_1.defaultBedrockRuntimeHttpAuthSchemeProvider,
httpAuthSchemes: config?.httpAuthSchemes ?? [
{
schemeId: "aws.auth#sigv4",
identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"),
signer: new core_1.AwsSdkSigV4Signer(),
},
{
schemeId: "smithy.api#httpBearerAuth",
identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#httpBearerAuth"),
signer: new core_2.HttpBearerAuthSigner(),
},
],
logger: config?.logger ?? new smithy_client_1.NoOpLogger(),
protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.bedrockruntime" }),
serviceId: config?.serviceId ?? "Bedrock Runtime",
urlParser: config?.urlParser ?? url_parser_1.parseUrl,
utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8,
utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8,
};
};
exports.getRuntimeConfig = getRuntimeConfig;

View File

@@ -0,0 +1,53 @@
'use strict';
var eventstreamSerdeUniversal = require('@smithy/eventstream-serde-universal');
var stream = require('stream');
async function* readabletoIterable(readStream) {
let streamEnded = false;
let generationEnded = false;
const records = new Array();
readStream.on("error", (err) => {
if (!streamEnded) {
streamEnded = true;
}
if (err) {
throw err;
}
});
readStream.on("data", (data) => {
records.push(data);
});
readStream.on("end", () => {
streamEnded = true;
});
while (!generationEnded) {
const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0));
if (value) {
yield value;
}
generationEnded = streamEnded && records.length === 0;
}
}
class EventStreamMarshaller {
universalMarshaller;
constructor({ utf8Encoder, utf8Decoder }) {
this.universalMarshaller = new eventstreamSerdeUniversal.EventStreamMarshaller({
utf8Decoder,
utf8Encoder,
});
}
deserialize(body, deserializer) {
const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body);
return this.universalMarshaller.deserialize(bodyIterable, deserializer);
}
serialize(input, serializer) {
return stream.Readable.from(this.universalMarshaller.serialize(input, serializer));
}
}
const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options);
exports.EventStreamMarshaller = EventStreamMarshaller;
exports.eventStreamSerdeProvider = eventStreamSerdeProvider;

View File

@@ -0,0 +1,132 @@
'use strict';
var eventstreamCodec = require('@smithy/eventstream-codec');
function getChunkedStream(source) {
let currentMessageTotalLength = 0;
let currentMessagePendingLength = 0;
let currentMessage = null;
let messageLengthBuffer = null;
const allocateMessage = (size) => {
if (typeof size !== "number") {
throw new Error("Attempted to allocate an event message where size was not a number: " + size);
}
currentMessageTotalLength = size;
currentMessagePendingLength = 4;
currentMessage = new Uint8Array(size);
const currentMessageView = new DataView(currentMessage.buffer);
currentMessageView.setUint32(0, size, false);
};
const iterator = async function* () {
const sourceIterator = source[Symbol.asyncIterator]();
while (true) {
const { value, done } = await sourceIterator.next();
if (done) {
if (!currentMessageTotalLength) {
return;
}
else if (currentMessageTotalLength === currentMessagePendingLength) {
yield currentMessage;
}
else {
throw new Error("Truncated event message received.");
}
return;
}
const chunkLength = value.length;
let currentOffset = 0;
while (currentOffset < chunkLength) {
if (!currentMessage) {
const bytesRemaining = chunkLength - currentOffset;
if (!messageLengthBuffer) {
messageLengthBuffer = new Uint8Array(4);
}
const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining);
messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength);
currentMessagePendingLength += numBytesForTotal;
currentOffset += numBytesForTotal;
if (currentMessagePendingLength < 4) {
break;
}
allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false));
messageLengthBuffer = null;
}
const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset);
currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength);
currentMessagePendingLength += numBytesToWrite;
currentOffset += numBytesToWrite;
if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) {
yield currentMessage;
currentMessage = null;
currentMessageTotalLength = 0;
currentMessagePendingLength = 0;
}
}
}
};
return {
[Symbol.asyncIterator]: iterator,
};
}
function getMessageUnmarshaller(deserializer, toUtf8) {
return async function (message) {
const { value: messageType } = message.headers[":message-type"];
if (messageType === "error") {
const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError");
unmodeledError.name = message.headers[":error-code"].value;
throw unmodeledError;
}
else if (messageType === "exception") {
const code = message.headers[":exception-type"].value;
const exception = { [code]: message };
const deserializedException = await deserializer(exception);
if (deserializedException.$unknown) {
const error = new Error(toUtf8(message.body));
error.name = code;
throw error;
}
throw deserializedException[code];
}
else if (messageType === "event") {
const event = {
[message.headers[":event-type"].value]: message,
};
const deserialized = await deserializer(event);
if (deserialized.$unknown)
return;
return deserialized;
}
else {
throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`);
}
};
}
class EventStreamMarshaller {
eventStreamCodec;
utfEncoder;
constructor({ utf8Encoder, utf8Decoder }) {
this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(utf8Encoder, utf8Decoder);
this.utfEncoder = utf8Encoder;
}
deserialize(body, deserializer) {
const inputStream = getChunkedStream(body);
return new eventstreamCodec.SmithyMessageDecoderStream({
messageStream: new eventstreamCodec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }),
deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder),
});
}
serialize(inputStream, serializer) {
return new eventstreamCodec.MessageEncoderStream({
messageStream: new eventstreamCodec.SmithyMessageEncoderStream({ inputStream, serializer }),
encoder: this.eventStreamCodec,
includeEndFrame: true,
});
}
}
const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options);
exports.EventStreamMarshaller = EventStreamMarshaller;
exports.eventStreamSerdeProvider = eventStreamSerdeProvider;

View File

@@ -0,0 +1,169 @@
'use strict';
var types = require('@smithy/types');
const getHttpHandlerExtensionConfiguration = (runtimeConfig) => {
return {
setHttpHandler(handler) {
runtimeConfig.httpHandler = handler;
},
httpHandler() {
return runtimeConfig.httpHandler;
},
updateHttpClientConfig(key, value) {
runtimeConfig.httpHandler?.updateHttpClientConfig(key, value);
},
httpHandlerConfigs() {
return runtimeConfig.httpHandler.httpHandlerConfigs();
},
};
};
const resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => {
return {
httpHandler: httpHandlerExtensionConfiguration.httpHandler(),
};
};
class Field {
name;
kind;
values;
constructor({ name, kind = types.FieldPosition.HEADER, values = [] }) {
this.name = name;
this.kind = kind;
this.values = values;
}
add(value) {
this.values.push(value);
}
set(values) {
this.values = values;
}
remove(value) {
this.values = this.values.filter((v) => v !== value);
}
toString() {
return this.values.map((v) => (v.includes(",") || v.includes(" ") ? `"${v}"` : v)).join(", ");
}
get() {
return this.values;
}
}
class Fields {
entries = {};
encoding;
constructor({ fields = [], encoding = "utf-8" }) {
fields.forEach(this.setField.bind(this));
this.encoding = encoding;
}
setField(field) {
this.entries[field.name.toLowerCase()] = field;
}
getField(name) {
return this.entries[name.toLowerCase()];
}
removeField(name) {
delete this.entries[name.toLowerCase()];
}
getByType(kind) {
return Object.values(this.entries).filter((field) => field.kind === kind);
}
}
class HttpRequest {
method;
protocol;
hostname;
port;
path;
query;
headers;
username;
password;
fragment;
body;
constructor(options) {
this.method = options.method || "GET";
this.hostname = options.hostname || "localhost";
this.port = options.port;
this.query = options.query || {};
this.headers = options.headers || {};
this.body = options.body;
this.protocol = options.protocol
? options.protocol.slice(-1) !== ":"
? `${options.protocol}:`
: options.protocol
: "https:";
this.path = options.path ? (options.path.charAt(0) !== "/" ? `/${options.path}` : options.path) : "/";
this.username = options.username;
this.password = options.password;
this.fragment = options.fragment;
}
static clone(request) {
const cloned = new HttpRequest({
...request,
headers: { ...request.headers },
});
if (cloned.query) {
cloned.query = cloneQuery(cloned.query);
}
return cloned;
}
static isInstance(request) {
if (!request) {
return false;
}
const req = request;
return ("method" in req &&
"protocol" in req &&
"hostname" in req &&
"path" in req &&
typeof req["query"] === "object" &&
typeof req["headers"] === "object");
}
clone() {
return HttpRequest.clone(this);
}
}
function cloneQuery(query) {
return Object.keys(query).reduce((carry, paramName) => {
const param = query[paramName];
return {
...carry,
[paramName]: Array.isArray(param) ? [...param] : param,
};
}, {});
}
class HttpResponse {
statusCode;
reason;
headers;
body;
constructor(options) {
this.statusCode = options.statusCode;
this.reason = options.reason;
this.headers = options.headers || {};
this.body = options.body;
}
static isInstance(response) {
if (!response)
return false;
const resp = response;
return typeof resp.statusCode === "number" && typeof resp.headers === "object";
}
}
function isValidHostname(hostname) {
const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/;
return hostPattern.test(hostname);
}
exports.Field = Field;
exports.Fields = Fields;
exports.HttpRequest = HttpRequest;
exports.HttpResponse = HttpResponse;
exports.getHttpHandlerExtensionConfiguration = getHttpHandlerExtensionConfiguration;
exports.isValidHostname = isValidHostname;
exports.resolveHttpHandlerRuntimeConfig = resolveHttpHandlerRuntimeConfig;

View File

@@ -0,0 +1,589 @@
'use strict';
var middlewareStack = require('@smithy/middleware-stack');
var protocols = require('@smithy/core/protocols');
var types = require('@smithy/types');
var schema = require('@smithy/core/schema');
var serde = require('@smithy/core/serde');
class Client {
config;
middlewareStack = middlewareStack.constructStack();
initConfig;
handlers;
constructor(config) {
this.config = config;
}
send(command, optionsOrCb, cb) {
const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined;
const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb;
const useHandlerCache = options === undefined && this.config.cacheMiddleware === true;
let handler;
if (useHandlerCache) {
if (!this.handlers) {
this.handlers = new WeakMap();
}
const handlers = this.handlers;
if (handlers.has(command.constructor)) {
handler = handlers.get(command.constructor);
}
else {
handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
handlers.set(command.constructor, handler);
}
}
else {
delete this.handlers;
handler = command.resolveMiddleware(this.middlewareStack, this.config, options);
}
if (callback) {
handler(command)
.then((result) => callback(null, result.output), (err) => callback(err))
.catch(() => { });
}
else {
return handler(command).then((result) => result.output);
}
}
destroy() {
this.config?.requestHandler?.destroy?.();
delete this.handlers;
}
}
const SENSITIVE_STRING$1 = "***SensitiveInformation***";
function schemaLogFilter(schema$1, data) {
if (data == null) {
return data;
}
const ns = schema.NormalizedSchema.of(schema$1);
if (ns.getMergedTraits().sensitive) {
return SENSITIVE_STRING$1;
}
if (ns.isListSchema()) {
const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive;
if (isSensitive) {
return SENSITIVE_STRING$1;
}
}
else if (ns.isMapSchema()) {
const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive;
if (isSensitive) {
return SENSITIVE_STRING$1;
}
}
else if (ns.isStructSchema() && typeof data === "object") {
const object = data;
const newObject = {};
for (const [member, memberNs] of ns.structIterator()) {
if (object[member] != null) {
newObject[member] = schemaLogFilter(memberNs, object[member]);
}
}
return newObject;
}
return data;
}
class Command {
middlewareStack = middlewareStack.constructStack();
schema;
static classBuilder() {
return new ClassBuilder();
}
resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor, }) {
for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) {
this.middlewareStack.use(mw);
}
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const handlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog,
outputFilterSensitiveLog,
[types.SMITHY_CONTEXT_KEY]: {
commandInstance: this,
...smithyContext,
},
...additionalContext,
};
const { requestHandler } = configuration;
return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext);
}
}
class ClassBuilder {
_init = () => { };
_ep = {};
_middlewareFn = () => [];
_commandName = "";
_clientName = "";
_additionalContext = {};
_smithyContext = {};
_inputFilterSensitiveLog = undefined;
_outputFilterSensitiveLog = undefined;
_serializer = null;
_deserializer = null;
_operationSchema;
init(cb) {
this._init = cb;
}
ep(endpointParameterInstructions) {
this._ep = endpointParameterInstructions;
return this;
}
m(middlewareSupplier) {
this._middlewareFn = middlewareSupplier;
return this;
}
s(service, operation, smithyContext = {}) {
this._smithyContext = {
service,
operation,
...smithyContext,
};
return this;
}
c(additionalContext = {}) {
this._additionalContext = additionalContext;
return this;
}
n(clientName, commandName) {
this._clientName = clientName;
this._commandName = commandName;
return this;
}
f(inputFilter = (_) => _, outputFilter = (_) => _) {
this._inputFilterSensitiveLog = inputFilter;
this._outputFilterSensitiveLog = outputFilter;
return this;
}
ser(serializer) {
this._serializer = serializer;
return this;
}
de(deserializer) {
this._deserializer = deserializer;
return this;
}
sc(operation) {
this._operationSchema = operation;
this._smithyContext.operationSchema = operation;
return this;
}
build() {
const closure = this;
let CommandRef;
return (CommandRef = class extends Command {
input;
static getEndpointParameterInstructions() {
return closure._ep;
}
constructor(...[input]) {
super();
this.input = input ?? {};
closure._init(this);
this.schema = closure._operationSchema;
}
resolveMiddleware(stack, configuration, options) {
const op = closure._operationSchema;
const input = op?.[4] ?? op?.input;
const output = op?.[5] ?? op?.output;
return this.resolveMiddlewareWithContext(stack, configuration, options, {
CommandCtor: CommandRef,
middlewareFn: closure._middlewareFn,
clientName: closure._clientName,
commandName: closure._commandName,
inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, input) : (_) => _),
outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op ? schemaLogFilter.bind(null, output) : (_) => _),
smithyContext: closure._smithyContext,
additionalContext: closure._additionalContext,
});
}
serialize = closure._serializer;
deserialize = closure._deserializer;
});
}
}
const SENSITIVE_STRING = "***SensitiveInformation***";
const createAggregatedClient = (commands, Client) => {
for (const command of Object.keys(commands)) {
const CommandCtor = commands[command];
const methodImpl = async function (args, optionsOrCb, cb) {
const command = new CommandCtor(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
}
else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object")
throw new Error(`Expected http options but got ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
}
else {
return this.send(command, optionsOrCb);
}
};
const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, "");
Client.prototype[methodName] = methodImpl;
}
};
class ServiceException extends Error {
$fault;
$response;
$retryable;
$metadata;
constructor(options) {
super(options.message);
Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype);
this.name = options.name;
this.$fault = options.$fault;
this.$metadata = options.$metadata;
}
static isInstance(value) {
if (!value)
return false;
const candidate = value;
return (ServiceException.prototype.isPrototypeOf(candidate) ||
(Boolean(candidate.$fault) &&
Boolean(candidate.$metadata) &&
(candidate.$fault === "client" || candidate.$fault === "server")));
}
static [Symbol.hasInstance](instance) {
if (!instance)
return false;
const candidate = instance;
if (this === ServiceException) {
return ServiceException.isInstance(instance);
}
if (ServiceException.isInstance(instance)) {
if (candidate.name && this.name) {
return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
}
return this.prototype.isPrototypeOf(instance);
}
return false;
}
}
const decorateServiceException = (exception, additions = {}) => {
Object.entries(additions)
.filter(([, v]) => v !== undefined)
.forEach(([k, v]) => {
if (exception[k] == undefined || exception[k] === "") {
exception[k] = v;
}
});
const message = exception.message || exception.Message || "UnknownError";
exception.message = message;
delete exception.Message;
return exception;
};
const throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => {
const $metadata = deserializeMetadata(output);
const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : undefined;
const response = new exceptionCtor({
name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError",
$fault: "client",
$metadata,
});
throw decorateServiceException(response, parsedBody);
};
const withBaseException = (ExceptionCtor) => {
return ({ output, parsedBody, errorCode }) => {
throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode });
};
};
const deserializeMetadata = (output) => ({
httpStatusCode: output.statusCode,
requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"],
extendedRequestId: output.headers["x-amz-id-2"],
cfId: output.headers["x-amz-cf-id"],
});
const loadConfigsForDefaultMode = (mode) => {
switch (mode) {
case "standard":
return {
retryMode: "standard",
connectionTimeout: 3100,
};
case "in-region":
return {
retryMode: "standard",
connectionTimeout: 1100,
};
case "cross-region":
return {
retryMode: "standard",
connectionTimeout: 3100,
};
case "mobile":
return {
retryMode: "standard",
connectionTimeout: 30000,
};
default:
return {};
}
};
let warningEmitted = false;
const emitWarningIfUnsupportedVersion = (version) => {
if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 16) {
warningEmitted = true;
}
};
const getChecksumConfiguration = (runtimeConfig) => {
const checksumAlgorithms = [];
for (const id in types.AlgorithmId) {
const algorithmId = types.AlgorithmId[id];
if (runtimeConfig[algorithmId] === undefined) {
continue;
}
checksumAlgorithms.push({
algorithmId: () => algorithmId,
checksumConstructor: () => runtimeConfig[algorithmId],
});
}
return {
addChecksumAlgorithm(algo) {
checksumAlgorithms.push(algo);
},
checksumAlgorithms() {
return checksumAlgorithms;
},
};
};
const resolveChecksumRuntimeConfig = (clientConfig) => {
const runtimeConfig = {};
clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
});
return runtimeConfig;
};
const getRetryConfiguration = (runtimeConfig) => {
return {
setRetryStrategy(retryStrategy) {
runtimeConfig.retryStrategy = retryStrategy;
},
retryStrategy() {
return runtimeConfig.retryStrategy;
},
};
};
const resolveRetryRuntimeConfig = (retryStrategyConfiguration) => {
const runtimeConfig = {};
runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy();
return runtimeConfig;
};
const getDefaultExtensionConfiguration = (runtimeConfig) => {
return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig));
};
const getDefaultClientConfiguration = getDefaultExtensionConfiguration;
const resolveDefaultRuntimeConfig = (config) => {
return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config));
};
const getArrayIfSingleItem = (mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray];
const getValueFromTextNode = (obj) => {
const textNodeName = "#text";
for (const key in obj) {
if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
obj[key] = obj[key][textNodeName];
}
else if (typeof obj[key] === "object" && obj[key] !== null) {
obj[key] = getValueFromTextNode(obj[key]);
}
}
return obj;
};
const isSerializableHeaderValue = (value) => {
return value != null;
};
class NoOpLogger {
trace() { }
debug() { }
info() { }
warn() { }
error() { }
}
function map(arg0, arg1, arg2) {
let target;
let filter;
let instructions;
if (typeof arg1 === "undefined" && typeof arg2 === "undefined") {
target = {};
instructions = arg0;
}
else {
target = arg0;
if (typeof arg1 === "function") {
filter = arg1;
instructions = arg2;
return mapWithFilter(target, filter, instructions);
}
else {
instructions = arg1;
}
}
for (const key of Object.keys(instructions)) {
if (!Array.isArray(instructions[key])) {
target[key] = instructions[key];
continue;
}
applyInstruction(target, null, instructions, key);
}
return target;
}
const convertMap = (target) => {
const output = {};
for (const [k, v] of Object.entries(target || {})) {
output[k] = [, v];
}
return output;
};
const take = (source, instructions) => {
const out = {};
for (const key in instructions) {
applyInstruction(out, source, instructions, key);
}
return out;
};
const mapWithFilter = (target, filter, instructions) => {
return map(target, Object.entries(instructions).reduce((_instructions, [key, value]) => {
if (Array.isArray(value)) {
_instructions[key] = value;
}
else {
if (typeof value === "function") {
_instructions[key] = [filter, value()];
}
else {
_instructions[key] = [filter, value];
}
}
return _instructions;
}, {}));
};
const applyInstruction = (target, source, instructions, targetKey) => {
if (source !== null) {
let instruction = instructions[targetKey];
if (typeof instruction === "function") {
instruction = [, instruction];
}
const [filter = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction;
if ((typeof filter === "function" && filter(source[sourceKey])) || (typeof filter !== "function" && !!filter)) {
target[targetKey] = valueFn(source[sourceKey]);
}
return;
}
let [filter, value] = instructions[targetKey];
if (typeof value === "function") {
let _value;
const defaultFilterPassed = filter === undefined && (_value = value()) != null;
const customFilterPassed = (typeof filter === "function" && !!filter(void 0)) || (typeof filter !== "function" && !!filter);
if (defaultFilterPassed) {
target[targetKey] = _value;
}
else if (customFilterPassed) {
target[targetKey] = value();
}
}
else {
const defaultFilterPassed = filter === undefined && value != null;
const customFilterPassed = (typeof filter === "function" && !!filter(value)) || (typeof filter !== "function" && !!filter);
if (defaultFilterPassed || customFilterPassed) {
target[targetKey] = value;
}
}
};
const nonNullish = (_) => _ != null;
const pass = (_) => _;
const serializeFloat = (value) => {
if (value !== value) {
return "NaN";
}
switch (value) {
case Infinity:
return "Infinity";
case -Infinity:
return "-Infinity";
default:
return value;
}
};
const serializeDateTime = (date) => date.toISOString().replace(".000Z", "Z");
const _json = (obj) => {
if (obj == null) {
return {};
}
if (Array.isArray(obj)) {
return obj.filter((_) => _ != null).map(_json);
}
if (typeof obj === "object") {
const target = {};
for (const key of Object.keys(obj)) {
if (obj[key] == null) {
continue;
}
target[key] = _json(obj[key]);
}
return target;
}
return obj;
};
Object.defineProperty(exports, "collectBody", {
enumerable: true,
get: function () { return protocols.collectBody; }
});
Object.defineProperty(exports, "extendedEncodeURIComponent", {
enumerable: true,
get: function () { return protocols.extendedEncodeURIComponent; }
});
Object.defineProperty(exports, "resolvedPath", {
enumerable: true,
get: function () { return protocols.resolvedPath; }
});
exports.Client = Client;
exports.Command = Command;
exports.NoOpLogger = NoOpLogger;
exports.SENSITIVE_STRING = SENSITIVE_STRING;
exports.ServiceException = ServiceException;
exports._json = _json;
exports.convertMap = convertMap;
exports.createAggregatedClient = createAggregatedClient;
exports.decorateServiceException = decorateServiceException;
exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion;
exports.getArrayIfSingleItem = getArrayIfSingleItem;
exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
exports.getDefaultExtensionConfiguration = getDefaultExtensionConfiguration;
exports.getValueFromTextNode = getValueFromTextNode;
exports.isSerializableHeaderValue = isSerializableHeaderValue;
exports.loadConfigsForDefaultMode = loadConfigsForDefaultMode;
exports.map = map;
exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;
exports.serializeDateTime = serializeDateTime;
exports.serializeFloat = serializeFloat;
exports.take = take;
exports.throwDefaultError = throwDefaultError;
exports.withBaseException = withBaseException;
Object.keys(serde).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return serde[k]; }
});
});

View File

@@ -0,0 +1,91 @@
'use strict';
exports.HttpAuthLocation = void 0;
(function (HttpAuthLocation) {
HttpAuthLocation["HEADER"] = "header";
HttpAuthLocation["QUERY"] = "query";
})(exports.HttpAuthLocation || (exports.HttpAuthLocation = {}));
exports.HttpApiKeyAuthLocation = void 0;
(function (HttpApiKeyAuthLocation) {
HttpApiKeyAuthLocation["HEADER"] = "header";
HttpApiKeyAuthLocation["QUERY"] = "query";
})(exports.HttpApiKeyAuthLocation || (exports.HttpApiKeyAuthLocation = {}));
exports.EndpointURLScheme = void 0;
(function (EndpointURLScheme) {
EndpointURLScheme["HTTP"] = "http";
EndpointURLScheme["HTTPS"] = "https";
})(exports.EndpointURLScheme || (exports.EndpointURLScheme = {}));
exports.AlgorithmId = void 0;
(function (AlgorithmId) {
AlgorithmId["MD5"] = "md5";
AlgorithmId["CRC32"] = "crc32";
AlgorithmId["CRC32C"] = "crc32c";
AlgorithmId["SHA1"] = "sha1";
AlgorithmId["SHA256"] = "sha256";
})(exports.AlgorithmId || (exports.AlgorithmId = {}));
const getChecksumConfiguration = (runtimeConfig) => {
const checksumAlgorithms = [];
if (runtimeConfig.sha256 !== undefined) {
checksumAlgorithms.push({
algorithmId: () => exports.AlgorithmId.SHA256,
checksumConstructor: () => runtimeConfig.sha256,
});
}
if (runtimeConfig.md5 != undefined) {
checksumAlgorithms.push({
algorithmId: () => exports.AlgorithmId.MD5,
checksumConstructor: () => runtimeConfig.md5,
});
}
return {
addChecksumAlgorithm(algo) {
checksumAlgorithms.push(algo);
},
checksumAlgorithms() {
return checksumAlgorithms;
},
};
};
const resolveChecksumRuntimeConfig = (clientConfig) => {
const runtimeConfig = {};
clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => {
runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor();
});
return runtimeConfig;
};
const getDefaultClientConfiguration = (runtimeConfig) => {
return getChecksumConfiguration(runtimeConfig);
};
const resolveDefaultRuntimeConfig = (config) => {
return resolveChecksumRuntimeConfig(config);
};
exports.FieldPosition = void 0;
(function (FieldPosition) {
FieldPosition[FieldPosition["HEADER"] = 0] = "HEADER";
FieldPosition[FieldPosition["TRAILER"] = 1] = "TRAILER";
})(exports.FieldPosition || (exports.FieldPosition = {}));
const SMITHY_CONTEXT_KEY = "__smithy_context";
exports.IniSectionType = void 0;
(function (IniSectionType) {
IniSectionType["PROFILE"] = "profile";
IniSectionType["SSO_SESSION"] = "sso-session";
IniSectionType["SERVICES"] = "services";
})(exports.IniSectionType || (exports.IniSectionType = {}));
exports.RequestHandlerProtocol = void 0;
(function (RequestHandlerProtocol) {
RequestHandlerProtocol["HTTP_0_9"] = "http/0.9";
RequestHandlerProtocol["HTTP_1_0"] = "http/1.0";
RequestHandlerProtocol["TDS_8_0"] = "tds/8.0";
})(exports.RequestHandlerProtocol || (exports.RequestHandlerProtocol = {}));
exports.SMITHY_CONTEXT_KEY = SMITHY_CONTEXT_KEY;
exports.getDefaultClientConfiguration = getDefaultClientConfiguration;
exports.resolveDefaultRuntimeConfig = resolveDefaultRuntimeConfig;

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromBase64 = void 0;
const util_buffer_from_1 = require("@smithy/util-buffer-from");
const BASE64_REGEX = /^[A-Za-z0-9+/]*={0,2}$/;
const fromBase64 = (input) => {
if ((input.length * 3) % 4 !== 0) {
throw new TypeError(`Incorrect padding on base64 string.`);
}
if (!BASE64_REGEX.exec(input)) {
throw new TypeError(`Invalid base64 string.`);
}
const buffer = (0, util_buffer_from_1.fromString)(input, "base64");
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
};
exports.fromBase64 = fromBase64;

View File

@@ -0,0 +1,19 @@
'use strict';
var fromBase64 = require('./fromBase64');
var toBase64 = require('./toBase64');
Object.keys(fromBase64).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return fromBase64[k]; }
});
});
Object.keys(toBase64).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return toBase64[k]; }
});
});

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toBase64 = void 0;
const util_buffer_from_1 = require("@smithy/util-buffer-from");
const util_utf8_1 = require("@smithy/util-utf8");
const toBase64 = (_input) => {
let input;
if (typeof _input === "string") {
input = (0, util_utf8_1.fromUtf8)(_input);
}
else {
input = _input;
}
if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") {
throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");
}
return (0, util_buffer_from_1.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("base64");
};
exports.toBase64 = toBase64;

View File

@@ -0,0 +1,20 @@
'use strict';
var isArrayBuffer = require('@smithy/is-array-buffer');
var buffer = require('buffer');
const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {
if (!isArrayBuffer.isArrayBuffer(input)) {
throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);
}
return buffer.Buffer.from(input, offset, length);
};
const fromString = (input, encoding) => {
if (typeof input !== "string") {
throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`);
}
return encoding ? buffer.Buffer.from(input, encoding) : buffer.Buffer.from(input);
};
exports.fromArrayBuffer = fromArrayBuffer;
exports.fromString = fromString;

View File

@@ -0,0 +1,6 @@
'use strict';
const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) ||
Object.prototype.toString.call(arg) === "[object ArrayBuffer]";
exports.isArrayBuffer = isArrayBuffer;

View File

@@ -0,0 +1,16 @@
import extraTypingsCommander from './index.js';
// wrapper to provide named exports for ESM.
export const {
program,
createCommand,
createArgument,
createOption,
CommanderError,
InvalidArgumentError,
InvalidOptionArgumentError, // deprecated old name
Command,
Argument,
Option,
Help,
} = extraTypingsCommander;

View File

@@ -0,0 +1,28 @@
const commander = require('commander');
exports = module.exports = {};
// Return a different global program than commander,
// and don't also return it as default export.
exports.program = new commander.Command();
/**
* Expose classes. The FooT versions are just types, so return Commander original implementations!
*/
exports.Argument = commander.Argument;
exports.Command = commander.Command;
exports.CommanderError = commander.CommanderError;
exports.Help = commander.Help;
exports.InvalidArgumentError = commander.InvalidArgumentError;
exports.InvalidOptionArgumentError = commander.InvalidArgumentError; // Deprecated
exports.Option = commander.Option;
// In Commander, the create routines end up being aliases for the matching
// methods on the global program due to the (deprecated) legacy default export.
// Here we roll our own, the way Commander might in future.
exports.createCommand = (name) => new commander.Command(name);
exports.createOption = (flags, description) =>
new commander.Option(flags, description);
exports.createArgument = (name, description) =>
new commander.Argument(name, description);

View File

@@ -0,0 +1,829 @@
import mutate from "dom-mutator";
import { decrypt, getAutoExperimentChangeType, isURLTargeted, loadSDKVersion, mergeQueryStrings, promiseTimeout } from "./util.mjs";
import { configureCache, refreshFeatures, startStreaming, unsubscribe } from "./feature-repository.mjs";
import { runExperiment, evalFeature as _evalFeature, getExperimentResult, getAllStickyBucketAssignmentDocs, decryptPayload, getApiHosts, getExperimentDedupeKey, getStickyBucketAttributes } from "./core.mjs";
const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
const SDK_VERSION = loadSDKVersion();
export class GrowthBook {
// context is technically private, but some tools depend on it so we can't mangle the name
// Properties and methods that start with "_" are mangled by Terser (saves ~150 bytes)
constructor(options) {
options = options || {};
// These properties are all initialized in the constructor instead of above
// This saves ~80 bytes in the final output
this.version = SDK_VERSION;
this._options = this.context = options;
this._renderer = options.renderer || null;
this._trackedExperiments = new Set();
this._completedChangeIds = new Set();
this._trackedFeatures = {};
this.debug = !!options.debug;
this._subscriptions = new Set();
this.ready = false;
this._assigned = new Map();
this._activeAutoExperiments = new Map();
this._triggeredExpKeys = new Set();
this._initialized = false;
this._redirectedUrl = "";
this._deferredTrackingCalls = new Map();
this._autoExperimentsAllowed = !options.disableExperimentsOnLoad;
this._destroyCallbacks = [];
this.logs = [];
this.log = this.log.bind(this);
this._saveDeferredTrack = this._saveDeferredTrack.bind(this);
this._fireSubscriptions = this._fireSubscriptions.bind(this);
this._recordChangedId = this._recordChangedId.bind(this);
if (options.remoteEval) {
if (options.decryptionKey) {
throw new Error("Encryption is not available for remoteEval");
}
if (!options.clientKey) {
throw new Error("Missing clientKey");
}
let isGbHost = false;
try {
isGbHost = !!new URL(options.apiHost || "").hostname.match(/growthbook\.io$/i);
} catch (e) {
// ignore invalid URLs
}
if (isGbHost) {
throw new Error("Cannot use remoteEval on GrowthBook Cloud");
}
} else {
if (options.cacheKeyAttributes) {
throw new Error("cacheKeyAttributes are only used for remoteEval");
}
}
if (options.stickyBucketService) {
const s = options.stickyBucketService;
this._saveStickyBucketAssignmentDoc = doc => {
return s.saveAssignments(doc);
};
}
if (options.plugins) {
for (const plugin of options.plugins) {
plugin(this);
}
}
if (options.features) {
this.ready = true;
}
if (isBrowser && options.enableDevMode) {
window._growthbook = this;
document.dispatchEvent(new Event("gbloaded"));
}
if (options.experiments) {
this.ready = true;
this._updateAllAutoExperiments();
}
// Hydrate sticky bucket service
if (this._options.stickyBucketService && this._options.stickyBucketAssignmentDocs) {
for (const key in this._options.stickyBucketAssignmentDocs) {
const doc = this._options.stickyBucketAssignmentDocs[key];
if (doc) {
this._options.stickyBucketService.saveAssignments(doc).catch(() => {
// Ignore hydration errors
});
}
}
}
// Legacy - passing in features/experiments into the constructor instead of using init
if (this.ready) {
this.refreshStickyBuckets(this.getPayload());
}
}
async setPayload(payload) {
this._payload = payload;
const data = await decryptPayload(payload, this._options.decryptionKey);
this._decryptedPayload = data;
await this.refreshStickyBuckets(data);
if (data.features) {
this._options.features = data.features;
}
if (data.savedGroups) {
this._options.savedGroups = data.savedGroups;
}
if (data.experiments) {
this._options.experiments = data.experiments;
this._updateAllAutoExperiments();
}
this.ready = true;
this._render();
}
initSync(options) {
this._initialized = true;
const payload = options.payload;
if (payload.encryptedExperiments || payload.encryptedFeatures) {
throw new Error("initSync does not support encrypted payloads");
}
if (this._options.stickyBucketService && !this._options.stickyBucketAssignmentDocs) {
this._options.stickyBucketAssignmentDocs = this.generateStickyBucketAssignmentDocsSync(this._options.stickyBucketService, payload);
}
this._payload = payload;
this._decryptedPayload = payload;
if (payload.features) {
this._options.features = payload.features;
}
if (payload.experiments) {
this._options.experiments = payload.experiments;
this._updateAllAutoExperiments();
}
this.ready = true;
startStreaming(this, options);
return this;
}
async init(options) {
this._initialized = true;
options = options || {};
if (options.cacheSettings) {
configureCache(options.cacheSettings);
}
if (options.payload) {
await this.setPayload(options.payload);
startStreaming(this, options);
return {
success: true,
source: "init"
};
} else {
const {
data,
...res
} = await this._refresh({
...options,
allowStale: true
});
startStreaming(this, options);
await this.setPayload(data || {});
return res;
}
}
/** @deprecated Use {@link init} */
async loadFeatures(options) {
options = options || {};
await this.init({
skipCache: options.skipCache,
timeout: options.timeout,
streaming: (this._options.backgroundSync ?? true) && (options.autoRefresh || this._options.subscribeToChanges)
});
}
async refreshFeatures(options) {
const res = await this._refresh({
...(options || {}),
allowStale: false
});
if (res.data) {
await this.setPayload(res.data);
}
}
getApiInfo() {
return [this.getApiHosts().apiHost, this.getClientKey()];
}
getApiHosts() {
return getApiHosts(this._options);
}
getClientKey() {
return this._options.clientKey || "";
}
getPayload() {
return this._payload || {
features: this.getFeatures(),
experiments: this.getExperiments()
};
}
getDecryptedPayload() {
return this._decryptedPayload || this.getPayload();
}
isRemoteEval() {
return this._options.remoteEval || false;
}
getCacheKeyAttributes() {
return this._options.cacheKeyAttributes;
}
async _refresh(_ref) {
let {
timeout,
skipCache,
allowStale,
streaming
} = _ref;
if (!this._options.clientKey) {
throw new Error("Missing clientKey");
}
// Trigger refresh in feature repository
return refreshFeatures({
instance: this,
timeout,
skipCache: skipCache || this._options.disableCache,
allowStale,
backgroundSync: streaming ?? this._options.backgroundSync ?? true
});
}
_render() {
if (this._renderer) {
try {
this._renderer();
} catch (e) {
console.error("Failed to render", e);
}
}
}
/** @deprecated Use {@link setPayload} */
setFeatures(features) {
this._options.features = features;
this.ready = true;
this._render();
}
/** @deprecated Use {@link setPayload} */
async setEncryptedFeatures(encryptedString, decryptionKey, subtle) {
const featuresJSON = await decrypt(encryptedString, decryptionKey || this._options.decryptionKey, subtle);
this.setFeatures(JSON.parse(featuresJSON));
}
/** @deprecated Use {@link setPayload} */
setExperiments(experiments) {
this._options.experiments = experiments;
this.ready = true;
this._updateAllAutoExperiments();
}
/** @deprecated Use {@link setPayload} */
async setEncryptedExperiments(encryptedString, decryptionKey, subtle) {
const experimentsJSON = await decrypt(encryptedString, decryptionKey || this._options.decryptionKey, subtle);
this.setExperiments(JSON.parse(experimentsJSON));
}
async setAttributes(attributes) {
this._options.attributes = attributes;
if (this._options.stickyBucketService) {
await this.refreshStickyBuckets();
}
if (this._options.remoteEval) {
await this._refreshForRemoteEval();
return;
}
this._render();
this._updateAllAutoExperiments();
}
async updateAttributes(attributes) {
return this.setAttributes({
...this._options.attributes,
...attributes
});
}
async setAttributeOverrides(overrides) {
this._options.attributeOverrides = overrides;
if (this._options.stickyBucketService) {
await this.refreshStickyBuckets();
}
if (this._options.remoteEval) {
await this._refreshForRemoteEval();
return;
}
this._render();
this._updateAllAutoExperiments();
}
async setForcedVariations(vars) {
this._options.forcedVariations = vars || {};
if (this._options.remoteEval) {
await this._refreshForRemoteEval();
return;
}
this._render();
this._updateAllAutoExperiments();
}
// eslint-disable-next-line
setForcedFeatures(map) {
this._options.forcedFeatureValues = map;
this._render();
}
async setURL(url) {
if (url === this._options.url) return;
this._options.url = url;
this._redirectedUrl = "";
if (this._options.remoteEval) {
await this._refreshForRemoteEval();
this._updateAllAutoExperiments(true);
return;
}
this._updateAllAutoExperiments(true);
}
getAttributes() {
return {
...this._options.attributes,
...this._options.attributeOverrides
};
}
getForcedVariations() {
return this._options.forcedVariations || {};
}
getForcedFeatures() {
// eslint-disable-next-line
return this._options.forcedFeatureValues || new Map();
}
getStickyBucketAssignmentDocs() {
return this._options.stickyBucketAssignmentDocs || {};
}
getUrl() {
return this._options.url || "";
}
getFeatures() {
return this._options.features || {};
}
getExperiments() {
return this._options.experiments || [];
}
getCompletedChangeIds() {
return Array.from(this._completedChangeIds);
}
subscribe(cb) {
this._subscriptions.add(cb);
return () => {
this._subscriptions.delete(cb);
};
}
async _refreshForRemoteEval() {
if (!this._options.remoteEval) return;
if (!this._initialized) return;
const res = await this._refresh({
allowStale: false
});
if (res.data) {
await this.setPayload(res.data);
}
}
getAllResults() {
return new Map(this._assigned);
}
onDestroy(cb) {
this._destroyCallbacks.push(cb);
}
isDestroyed() {
return !!this._destroyed;
}
destroy() {
this._destroyed = true;
// Custom callbacks
// Do this first in case it needs access to the below data that is cleared
this._destroyCallbacks.forEach(cb => {
try {
cb();
} catch (e) {
console.error(e);
}
});
// Release references to save memory
this._subscriptions.clear();
this._assigned.clear();
this._trackedExperiments.clear();
this._completedChangeIds.clear();
this._deferredTrackingCalls.clear();
this._trackedFeatures = {};
this._destroyCallbacks = [];
this._payload = undefined;
this._saveStickyBucketAssignmentDoc = undefined;
unsubscribe(this);
this.logs = [];
if (isBrowser && window._growthbook === this) {
delete window._growthbook;
}
// Undo any active auto experiments
this._activeAutoExperiments.forEach(exp => {
exp.undo();
});
this._activeAutoExperiments.clear();
this._triggeredExpKeys.clear();
}
setRenderer(renderer) {
this._renderer = renderer;
}
forceVariation(key, variation) {
this._options.forcedVariations = this._options.forcedVariations || {};
this._options.forcedVariations[key] = variation;
if (this._options.remoteEval) {
this._refreshForRemoteEval();
return;
}
this._updateAllAutoExperiments();
this._render();
}
run(experiment) {
const {
result
} = runExperiment(experiment, null, this._getEvalContext());
this._fireSubscriptions(experiment, result);
return result;
}
triggerExperiment(key) {
this._triggeredExpKeys.add(key);
if (!this._options.experiments) return null;
const experiments = this._options.experiments.filter(exp => exp.key === key);
return experiments.map(exp => {
return this._runAutoExperiment(exp);
}).filter(res => res !== null);
}
triggerAutoExperiments() {
this._autoExperimentsAllowed = true;
this._updateAllAutoExperiments(true);
}
_getEvalContext() {
return {
user: this._getUserContext(),
global: this._getGlobalContext(),
stack: {
evaluatedFeatures: new Set()
}
};
}
_getUserContext() {
return {
attributes: this._options.user ? {
...this._options.user,
...this._options.attributes
} : this._options.attributes,
enableDevMode: this._options.enableDevMode,
blockedChangeIds: this._options.blockedChangeIds,
stickyBucketAssignmentDocs: this._options.stickyBucketAssignmentDocs,
url: this._getContextUrl(),
forcedVariations: this._options.forcedVariations,
forcedFeatureValues: this._options.forcedFeatureValues,
attributeOverrides: this._options.attributeOverrides,
saveStickyBucketAssignmentDoc: this._saveStickyBucketAssignmentDoc,
trackingCallback: this._options.trackingCallback,
onFeatureUsage: this._options.onFeatureUsage,
devLogs: this.logs,
trackedExperiments: this._trackedExperiments,
trackedFeatureUsage: this._trackedFeatures
};
}
_getGlobalContext() {
return {
features: this._options.features,
experiments: this._options.experiments,
log: this.log,
enabled: this._options.enabled,
qaMode: this._options.qaMode,
savedGroups: this._options.savedGroups,
groups: this._options.groups,
overrides: this._options.overrides,
onExperimentEval: this._subscriptions.size > 0 ? this._fireSubscriptions : undefined,
recordChangeId: this._recordChangedId,
saveDeferredTrack: this._saveDeferredTrack,
eventLogger: this._options.eventLogger
};
}
_runAutoExperiment(experiment, forceRerun) {
const existing = this._activeAutoExperiments.get(experiment);
// If this is a manual experiment and it's not already running, skip
if (experiment.manual && !this._triggeredExpKeys.has(experiment.key) && !existing) return null;
// Check if this particular experiment is blocked by options settings
// For example, if all visualEditor experiments are disabled
const isBlocked = this._isAutoExperimentBlockedByContext(experiment);
if (isBlocked) {
process.env.NODE_ENV !== "production" && this.log("Auto experiment blocked", {
id: experiment.key
});
}
let result;
let trackingCall;
// Run the experiment (if blocked exclude)
if (isBlocked) {
result = getExperimentResult(this._getEvalContext(), experiment, -1, false, "");
} else {
({
result,
trackingCall
} = runExperiment(experiment, null, this._getEvalContext()));
this._fireSubscriptions(experiment, result);
}
// A hash to quickly tell if the assigned value changed
const valueHash = JSON.stringify(result.value);
// If the changes are already active, no need to re-apply them
if (!forceRerun && result.inExperiment && existing && existing.valueHash === valueHash) {
return result;
}
// Undo any existing changes
if (existing) this._undoActiveAutoExperiment(experiment);
// Apply new changes
if (result.inExperiment) {
const changeType = getAutoExperimentChangeType(experiment);
if (changeType === "redirect" && result.value.urlRedirect && experiment.urlPatterns) {
const url = experiment.persistQueryString ? mergeQueryStrings(this._getContextUrl(), result.value.urlRedirect) : result.value.urlRedirect;
if (isURLTargeted(url, experiment.urlPatterns)) {
this.log("Skipping redirect because original URL matches redirect URL", {
id: experiment.key
});
return result;
}
this._redirectedUrl = url;
const {
navigate,
delay
} = this._getNavigateFunction();
if (navigate) {
if (isBrowser) {
// Wait for the possibly-async tracking callback, bound by min and max delays
Promise.all([...(trackingCall ? [promiseTimeout(trackingCall, this._options.maxNavigateDelay ?? 1000)] : []), new Promise(resolve => window.setTimeout(resolve, this._options.navigateDelay ?? delay))]).then(() => {
try {
navigate(url);
} catch (e) {
console.error(e);
}
});
} else {
try {
navigate(url);
} catch (e) {
console.error(e);
}
}
}
} else if (changeType === "visual") {
const undo = this._options.applyDomChangesCallback ? this._options.applyDomChangesCallback(result.value) : this._applyDOMChanges(result.value);
if (undo) {
this._activeAutoExperiments.set(experiment, {
undo,
valueHash
});
}
}
}
return result;
}
_undoActiveAutoExperiment(exp) {
const data = this._activeAutoExperiments.get(exp);
if (data) {
data.undo();
this._activeAutoExperiments.delete(exp);
}
}
_updateAllAutoExperiments(forceRerun) {
if (!this._autoExperimentsAllowed) return;
const experiments = this._options.experiments || [];
// Stop any experiments that are no longer defined
const keys = new Set(experiments);
this._activeAutoExperiments.forEach((v, k) => {
if (!keys.has(k)) {
v.undo();
this._activeAutoExperiments.delete(k);
}
});
// Re-run all new/updated experiments
for (const exp of experiments) {
const result = this._runAutoExperiment(exp, forceRerun);
// Once you're in a redirect experiment, break out of the loop and don't run any further experiments
if (result !== null && result !== void 0 && result.inExperiment && getAutoExperimentChangeType(exp) === "redirect") {
break;
}
}
}
_fireSubscriptions(experiment, result) {
const key = experiment.key;
// If assigned variation has changed, fire subscriptions
const prev = this._assigned.get(key);
// TODO: what if the experiment definition has changed?
if (!prev || prev.result.inExperiment !== result.inExperiment || prev.result.variationId !== result.variationId) {
this._assigned.set(key, {
experiment,
result
});
this._subscriptions.forEach(cb => {
try {
cb(experiment, result);
} catch (e) {
console.error(e);
}
});
}
}
_recordChangedId(id) {
this._completedChangeIds.add(id);
}
isOn(key) {
return this.evalFeature(key).on;
}
isOff(key) {
return this.evalFeature(key).off;
}
getFeatureValue(key, defaultValue) {
const value = this.evalFeature(key).value;
return value === null ? defaultValue : value;
}
/**
* @deprecated Use {@link evalFeature}
* @param id
*/
// eslint-disable-next-line
feature(id) {
return this.evalFeature(id);
}
evalFeature(id) {
return _evalFeature(id, this._getEvalContext());
}
log(msg, ctx) {
if (!this.debug) return;
if (this._options.log) this._options.log(msg, ctx);else console.log(msg, ctx);
}
getDeferredTrackingCalls() {
return Array.from(this._deferredTrackingCalls.values());
}
setDeferredTrackingCalls(calls) {
this._deferredTrackingCalls = new Map(calls.filter(c => c && c.experiment && c.result).map(c => {
return [getExperimentDedupeKey(c.experiment, c.result), c];
}));
}
async fireDeferredTrackingCalls() {
if (!this._options.trackingCallback) return;
const promises = [];
this._deferredTrackingCalls.forEach(call => {
if (!call || !call.experiment || !call.result) {
console.error("Invalid deferred tracking call", {
call: call
});
} else {
promises.push(this._options.trackingCallback(call.experiment, call.result));
}
});
this._deferredTrackingCalls.clear();
await Promise.all(promises);
}
setTrackingCallback(callback) {
this._options.trackingCallback = callback;
this.fireDeferredTrackingCalls();
}
setEventLogger(logger) {
this._options.eventLogger = logger;
}
async logEvent(eventName, properties) {
if (this._destroyed) {
console.error("Cannot log event to destroyed GrowthBook instance");
return;
}
if (this._options.enableDevMode) {
this.logs.push({
eventName,
properties,
timestamp: Date.now().toString(),
logType: "event"
});
}
if (this._options.eventLogger) {
try {
await this._options.eventLogger(eventName, properties || {}, this._getUserContext());
} catch (e) {
console.error(e);
}
} else {
console.error("No event logger configured");
}
}
_saveDeferredTrack(data) {
this._deferredTrackingCalls.set(getExperimentDedupeKey(data.experiment, data.result), data);
}
_getContextUrl() {
return this._options.url || (isBrowser ? window.location.href : "");
}
_isAutoExperimentBlockedByContext(experiment) {
const changeType = getAutoExperimentChangeType(experiment);
if (changeType === "visual") {
if (this._options.disableVisualExperiments) return true;
if (this._options.disableJsInjection) {
if (experiment.variations.some(v => v.js)) {
return true;
}
}
} else if (changeType === "redirect") {
if (this._options.disableUrlRedirectExperiments) return true;
// Validate URLs
try {
const current = new URL(this._getContextUrl());
for (const v of experiment.variations) {
if (!v || !v.urlRedirect) continue;
const url = new URL(v.urlRedirect);
// If we're blocking cross origin redirects, block if the protocol or host is different
if (this._options.disableCrossOriginUrlRedirectExperiments) {
if (url.protocol !== current.protocol) return true;
if (url.host !== current.host) return true;
}
}
} catch (e) {
// Problem parsing one of the URLs
this.log("Error parsing current or redirect URL", {
id: experiment.key,
error: e
});
return true;
}
} else {
// Block any unknown changeTypes
return true;
}
if (experiment.changeId && (this._options.blockedChangeIds || []).includes(experiment.changeId)) {
return true;
}
return false;
}
getRedirectUrl() {
return this._redirectedUrl;
}
_getNavigateFunction() {
if (this._options.navigate) {
return {
navigate: this._options.navigate,
delay: 0
};
} else if (isBrowser) {
return {
navigate: url => {
window.location.replace(url);
},
delay: 100
};
}
return {
navigate: null,
delay: 0
};
}
_applyDOMChanges(changes) {
if (!isBrowser) return;
const undo = [];
if (changes.css) {
const s = document.createElement("style");
s.innerHTML = changes.css;
document.head.appendChild(s);
undo.push(() => s.remove());
}
if (changes.js) {
const script = document.createElement("script");
script.innerHTML = changes.js;
if (this._options.jsInjectionNonce) {
script.nonce = this._options.jsInjectionNonce;
}
document.head.appendChild(script);
undo.push(() => script.remove());
}
if (changes.domMutations) {
changes.domMutations.forEach(mutation => {
undo.push(mutate.declarative(mutation).revert);
});
}
return () => {
undo.forEach(fn => fn());
};
}
async refreshStickyBuckets(data) {
if (this._options.stickyBucketService) {
const ctx = this._getEvalContext();
const docs = await getAllStickyBucketAssignmentDocs(ctx, this._options.stickyBucketService, data);
this._options.stickyBucketAssignmentDocs = docs;
}
}
generateStickyBucketAssignmentDocsSync(stickyBucketService, payload) {
if (!("getAllAssignmentsSync" in stickyBucketService)) {
console.error("generating StickyBucketAssignmentDocs docs requires StickyBucketServiceSync");
return;
}
const ctx = this._getEvalContext();
const attributes = getStickyBucketAttributes(ctx, payload);
return stickyBucketService.getAllAssignmentsSync(attributes);
}
inDevMode() {
return !!this._options.enableDevMode;
}
}
export async function prefetchPayload(options) {
// Create a temporary instance, just to fetch the payload
const instance = new GrowthBook(options);
await refreshFeatures({
instance,
skipCache: options.skipCache,
allowStale: false,
backgroundSync: options.streaming
});
instance.destroy();
}
//# sourceMappingURL=GrowthBook.mjs.map

View File

@@ -0,0 +1,879 @@
import { evalCondition } from "./mongrule.mjs";
import { chooseVariation, decrypt, getBucketRanges, getQueryStringOverride, getUrlRegExp, hash, inNamespace, inRange, isIncluded, isURLTargeted, toString } from "./util.mjs";
export const EVENT_FEATURE_EVALUATED = "Feature Evaluated";
export const EVENT_EXPERIMENT_VIEWED = "Experiment Viewed";
function getForcedFeatureValues(ctx) {
// Merge user and global values
const ret = new Map();
if (ctx.global.forcedFeatureValues) {
ctx.global.forcedFeatureValues.forEach((v, k) => ret.set(k, v));
}
if (ctx.user.forcedFeatureValues) {
ctx.user.forcedFeatureValues.forEach((v, k) => ret.set(k, v));
}
return ret;
}
function getForcedVariations(ctx) {
// Merge user and global values
if (ctx.global.forcedVariations && ctx.user.forcedVariations) {
return {
...ctx.global.forcedVariations,
...ctx.user.forcedVariations
};
} else if (ctx.global.forcedVariations) {
return ctx.global.forcedVariations;
} else if (ctx.user.forcedVariations) {
return ctx.user.forcedVariations;
} else {
return {};
}
}
async function safeCall(fn) {
try {
await fn();
} catch (e) {
// Do nothing
}
}
function onExperimentViewed(ctx, experiment, result) {
// Make sure a tracking callback is only fired once per unique experiment
if (ctx.user.trackedExperiments) {
const k = getExperimentDedupeKey(experiment, result);
if (ctx.user.trackedExperiments.has(k)) {
return [];
}
ctx.user.trackedExperiments.add(k);
}
if (ctx.user.enableDevMode && ctx.user.devLogs) {
ctx.user.devLogs.push({
experiment,
result,
timestamp: Date.now().toString(),
logType: "experiment"
});
}
const calls = [];
if (ctx.global.trackingCallback) {
const cb = ctx.global.trackingCallback;
calls.push(safeCall(() => cb(experiment, result, ctx.user)));
}
if (ctx.user.trackingCallback) {
const cb = ctx.user.trackingCallback;
calls.push(safeCall(() => cb(experiment, result)));
}
if (ctx.global.eventLogger) {
const cb = ctx.global.eventLogger;
calls.push(safeCall(() => cb(EVENT_EXPERIMENT_VIEWED, {
experimentId: experiment.key,
variationId: result.key,
hashAttribute: result.hashAttribute,
hashValue: result.hashValue
}, ctx.user)));
}
return calls;
}
function onFeatureUsage(ctx, key, ret) {
// Only track a feature once, unless the assigned value changed
if (ctx.user.trackedFeatureUsage) {
const stringifiedValue = JSON.stringify(ret.value);
if (ctx.user.trackedFeatureUsage[key] === stringifiedValue) return;
ctx.user.trackedFeatureUsage[key] = stringifiedValue;
if (ctx.user.enableDevMode && ctx.user.devLogs) {
ctx.user.devLogs.push({
featureKey: key,
result: ret,
timestamp: Date.now().toString(),
logType: "feature"
});
}
}
if (ctx.global.onFeatureUsage) {
const cb = ctx.global.onFeatureUsage;
safeCall(() => cb(key, ret, ctx.user));
}
if (ctx.user.onFeatureUsage) {
const cb = ctx.user.onFeatureUsage;
safeCall(() => cb(key, ret));
}
if (ctx.global.eventLogger) {
const cb = ctx.global.eventLogger;
safeCall(() => cb(EVENT_FEATURE_EVALUATED, {
feature: key,
source: ret.source,
value: ret.value,
ruleId: ret.source === "defaultValue" ? "$default" : ret.ruleId || "",
variationId: ret.experimentResult ? ret.experimentResult.key : ""
}, ctx.user));
}
}
export function evalFeature(id, ctx) {
if (ctx.stack.evaluatedFeatures.has(id)) {
process.env.NODE_ENV !== "production" && ctx.global.log(`evalFeature: circular dependency detected: ${ctx.stack.id} -> ${id}`, {
from: ctx.stack.id,
to: id
});
return getFeatureResult(ctx, id, null, "cyclicPrerequisite");
}
ctx.stack.evaluatedFeatures.add(id);
ctx.stack.id = id;
// Global override
const forcedValues = getForcedFeatureValues(ctx);
if (forcedValues.has(id)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Global override", {
id,
value: forcedValues.get(id)
});
return getFeatureResult(ctx, id, forcedValues.get(id), "override");
}
// Unknown feature id
if (!ctx.global.features || !ctx.global.features[id]) {
process.env.NODE_ENV !== "production" && ctx.global.log("Unknown feature", {
id
});
return getFeatureResult(ctx, id, null, "unknownFeature");
}
// Get the feature
const feature = ctx.global.features[id];
// Loop through the rules
if (feature.rules) {
const evaluatedFeatures = new Set(ctx.stack.evaluatedFeatures);
rules: for (const rule of feature.rules) {
// If there are prerequisite flag(s), evaluate them
if (rule.parentConditions) {
for (const parentCondition of rule.parentConditions) {
ctx.stack.evaluatedFeatures = new Set(evaluatedFeatures);
const parentResult = evalFeature(parentCondition.id, ctx);
// break out for cyclic prerequisites
if (parentResult.source === "cyclicPrerequisite") {
return getFeatureResult(ctx, id, null, "cyclicPrerequisite");
}
const evalObj = {
value: parentResult.value
};
const evaled = evalCondition(evalObj, parentCondition.condition || {});
if (!evaled) {
// blocking prerequisite eval failed: feature evaluation fails
if (parentCondition.gate) {
process.env.NODE_ENV !== "production" && ctx.global.log("Feature blocked by prerequisite", {
id,
rule
});
return getFeatureResult(ctx, id, null, "prerequisite");
}
// non-blocking prerequisite eval failed: break out of parentConditions loop, jump to the next rule
process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because prerequisite evaluation fails", {
id,
rule
});
continue rules;
}
}
}
// If there are filters for who is included (e.g. namespaces)
if (rule.filters && isFilteredOut(rule.filters, ctx)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because of filters", {
id,
rule
});
continue;
}
// Feature value is being forced
if ("force" in rule) {
// If it's a conditional rule, skip if the condition doesn't pass
if (rule.condition && !conditionPasses(rule.condition, ctx)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because of condition ff", {
id,
rule
});
continue;
}
// If this is a percentage rollout, skip if not included
if (!isIncludedInRollout(ctx, rule.seed || id, rule.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !rule.disableStickyBucketing ? rule.fallbackAttribute : undefined, rule.range, rule.coverage, rule.hashVersion)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip rule because user not included in rollout", {
id,
rule
});
continue;
}
process.env.NODE_ENV !== "production" && ctx.global.log("Force value from rule", {
id,
rule
});
// If this was a remotely evaluated experiment, fire the tracking callbacks
if (rule.tracks) {
rule.tracks.forEach(t => {
const calls = onExperimentViewed(ctx, t.experiment, t.result);
if (!calls.length && ctx.global.saveDeferredTrack) {
ctx.global.saveDeferredTrack({
experiment: t.experiment,
result: t.result
});
}
});
}
return getFeatureResult(ctx, id, rule.force, "force", rule.id);
}
if (!rule.variations) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip invalid rule", {
id,
rule
});
continue;
}
// For experiment rules, run an experiment
const exp = {
variations: rule.variations,
key: rule.key || id
};
if ("coverage" in rule) exp.coverage = rule.coverage;
if (rule.weights) exp.weights = rule.weights;
if (rule.hashAttribute) exp.hashAttribute = rule.hashAttribute;
if (rule.fallbackAttribute) exp.fallbackAttribute = rule.fallbackAttribute;
if (rule.disableStickyBucketing) exp.disableStickyBucketing = rule.disableStickyBucketing;
if (rule.bucketVersion !== undefined) exp.bucketVersion = rule.bucketVersion;
if (rule.minBucketVersion !== undefined) exp.minBucketVersion = rule.minBucketVersion;
if (rule.namespace) exp.namespace = rule.namespace;
if (rule.meta) exp.meta = rule.meta;
if (rule.ranges) exp.ranges = rule.ranges;
if (rule.name) exp.name = rule.name;
if (rule.phase) exp.phase = rule.phase;
if (rule.seed) exp.seed = rule.seed;
if (rule.hashVersion) exp.hashVersion = rule.hashVersion;
if (rule.filters) exp.filters = rule.filters;
if (rule.condition) exp.condition = rule.condition;
// Only return a value if the user is part of the experiment
const {
result
} = runExperiment(exp, id, ctx);
ctx.global.onExperimentEval && ctx.global.onExperimentEval(exp, result);
if (result.inExperiment && !result.passthrough) {
return getFeatureResult(ctx, id, result.value, "experiment", rule.id, exp, result);
}
}
}
process.env.NODE_ENV !== "production" && ctx.global.log("Use default value", {
id,
value: feature.defaultValue
});
// Fall back to using the default value
return getFeatureResult(ctx, id, feature.defaultValue === undefined ? null : feature.defaultValue, "defaultValue");
}
export function runExperiment(experiment, featureId, ctx) {
const key = experiment.key;
const numVariations = experiment.variations.length;
// 1. If experiment has less than 2 variations, return immediately
if (numVariations < 2) {
process.env.NODE_ENV !== "production" && ctx.global.log("Invalid experiment", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 2. If the context is disabled, return immediately
if (ctx.global.enabled === false || ctx.user.enabled === false) {
process.env.NODE_ENV !== "production" && ctx.global.log("Context disabled", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 2.5. Merge in experiment overrides from the context
experiment = mergeOverrides(experiment, ctx);
// 2.6 New, more powerful URL targeting
if (experiment.urlPatterns && !isURLTargeted(ctx.user.url || "", experiment.urlPatterns)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of url targeting", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 3. If a variation is forced from a querystring, return the forced variation
const qsOverride = getQueryStringOverride(key, ctx.user.url || "", numVariations);
if (qsOverride !== null) {
process.env.NODE_ENV !== "production" && ctx.global.log("Force via querystring", {
id: key,
variation: qsOverride
});
return {
result: getExperimentResult(ctx, experiment, qsOverride, false, featureId)
};
}
// 4. If a variation is forced in the context, return the forced variation
const forcedVariations = getForcedVariations(ctx);
if (key in forcedVariations) {
const variation = forcedVariations[key];
process.env.NODE_ENV !== "production" && ctx.global.log("Force via dev tools", {
id: key,
variation
});
return {
result: getExperimentResult(ctx, experiment, variation, false, featureId)
};
}
// 5. Exclude if a draft experiment or not active
if (experiment.status === "draft" || experiment.active === false) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because inactive", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 6. Get the hash attribute and return if empty
const {
hashAttribute,
hashValue
} = getHashAttribute(ctx, experiment.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing ? experiment.fallbackAttribute : undefined);
if (!hashValue) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because missing hashAttribute", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
let assigned = -1;
let foundStickyBucket = false;
let stickyBucketVersionIsBlocked = false;
if (ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing) {
const {
variation,
versionIsBlocked
} = getStickyBucketVariation({
ctx,
expKey: experiment.key,
expBucketVersion: experiment.bucketVersion,
expHashAttribute: experiment.hashAttribute,
expFallbackAttribute: experiment.fallbackAttribute,
expMinBucketVersion: experiment.minBucketVersion,
expMeta: experiment.meta
});
foundStickyBucket = variation >= 0;
assigned = variation;
stickyBucketVersionIsBlocked = !!versionIsBlocked;
}
// Some checks are not needed if we already have a sticky bucket
if (!foundStickyBucket) {
// 7. Exclude if user is filtered out (used to be called "namespace")
if (experiment.filters) {
if (isFilteredOut(experiment.filters, ctx)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of filters", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
} else if (experiment.namespace && !inNamespace(hashValue, experiment.namespace)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of namespace", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 7.5. Exclude if experiment.include returns false or throws
if (experiment.include && !isIncluded(experiment.include)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of include function", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 8. Exclude if condition is false
if (experiment.condition && !conditionPasses(experiment.condition, ctx)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of condition exp", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 8.05. Exclude if prerequisites are not met
if (experiment.parentConditions) {
const evaluatedFeatures = new Set(ctx.stack.evaluatedFeatures);
for (const parentCondition of experiment.parentConditions) {
ctx.stack.evaluatedFeatures = new Set(evaluatedFeatures);
const parentResult = evalFeature(parentCondition.id, ctx);
// break out for cyclic prerequisites
if (parentResult.source === "cyclicPrerequisite") {
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
const evalObj = {
value: parentResult.value
};
if (!evalCondition(evalObj, parentCondition.condition || {})) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because prerequisite evaluation fails", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
}
}
// 8.1. Exclude if user is not in a required group
if (experiment.groups && !hasGroupOverlap(experiment.groups, ctx)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of groups", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
}
// 8.2. Old style URL targeting
if (experiment.url && !urlIsValid(experiment.url, ctx)) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of url", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 9. Get the variation from the sticky bucket or get bucket ranges and choose variation
const n = hash(experiment.seed || key, hashValue, experiment.hashVersion || 1);
if (n === null) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of invalid hash version", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
if (!foundStickyBucket) {
const ranges = experiment.ranges || getBucketRanges(numVariations, experiment.coverage === undefined ? 1 : experiment.coverage, experiment.weights);
assigned = chooseVariation(n, ranges);
}
// 9.5 Unenroll if any prior sticky buckets are blocked by version
if (stickyBucketVersionIsBlocked) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because sticky bucket version is blocked", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId, undefined, true)
};
}
// 10. Return if not in experiment
if (assigned < 0) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because of coverage", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 11. Experiment has a forced variation
if ("force" in experiment) {
process.env.NODE_ENV !== "production" && ctx.global.log("Force variation", {
id: key,
variation: experiment.force
});
return {
result: getExperimentResult(ctx, experiment, experiment.force === undefined ? -1 : experiment.force, false, featureId)
};
}
// 12. Exclude if in QA mode
if (ctx.global.qaMode || ctx.user.qaMode) {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because QA mode", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 12.5. Exclude if experiment is stopped
if (experiment.status === "stopped") {
process.env.NODE_ENV !== "production" && ctx.global.log("Skip because stopped", {
id: key
});
return {
result: getExperimentResult(ctx, experiment, -1, false, featureId)
};
}
// 13. Build the result object
const result = getExperimentResult(ctx, experiment, assigned, true, featureId, n, foundStickyBucket);
// 13.5. Persist sticky bucket
if (ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing) {
const {
changed,
key: attrKey,
doc
} = generateStickyBucketAssignmentDoc(ctx, hashAttribute, toString(hashValue), {
[getStickyBucketExperimentKey(experiment.key, experiment.bucketVersion)]: result.key
});
if (changed) {
// update local docs
ctx.user.stickyBucketAssignmentDocs = ctx.user.stickyBucketAssignmentDocs || {};
ctx.user.stickyBucketAssignmentDocs[attrKey] = doc;
// save doc
ctx.user.saveStickyBucketAssignmentDoc(doc);
}
}
// 14. Fire the tracking callback(s)
// Store the promise in case we're awaiting it (ex: browser url redirects)
const trackingCalls = onExperimentViewed(ctx, experiment, result);
if (trackingCalls.length === 0 && ctx.global.saveDeferredTrack) {
ctx.global.saveDeferredTrack({
experiment,
result
});
}
const trackingCall = !trackingCalls.length ? undefined : trackingCalls.length === 1 ? trackingCalls[0] : Promise.all(trackingCalls).then(() => {});
// 14.1 Keep track of completed changeIds
"changeId" in experiment && experiment.changeId && ctx.global.recordChangeId && ctx.global.recordChangeId(experiment.changeId);
// 15. Return the result
process.env.NODE_ENV !== "production" && ctx.global.log("In experiment", {
id: key,
variation: result.variationId
});
return {
result,
trackingCall
};
}
function getFeatureResult(ctx, key, value, source, ruleId, experiment, result) {
const ret = {
value,
on: !!value,
off: !value,
source,
ruleId: ruleId || ""
};
if (experiment) ret.experiment = experiment;
if (result) ret.experimentResult = result;
// Track the usage of this feature in real-time
if (source !== "override") {
onFeatureUsage(ctx, key, ret);
}
return ret;
}
function getAttributes(ctx) {
return {
...ctx.user.attributes,
...ctx.user.attributeOverrides
};
}
function conditionPasses(condition, ctx) {
return evalCondition(getAttributes(ctx), condition, ctx.global.savedGroups || {});
}
function isFilteredOut(filters, ctx) {
return filters.some(filter => {
const {
hashValue
} = getHashAttribute(ctx, filter.attribute);
if (!hashValue) return true;
const n = hash(filter.seed, hashValue, filter.hashVersion || 2);
if (n === null) return true;
return !filter.ranges.some(r => inRange(n, r));
});
}
function isIncludedInRollout(ctx, seed, hashAttribute, fallbackAttribute, range, coverage, hashVersion) {
if (!range && coverage === undefined) return true;
if (!range && coverage === 0) return false;
const {
hashValue
} = getHashAttribute(ctx, hashAttribute, fallbackAttribute);
if (!hashValue) {
return false;
}
const n = hash(seed, hashValue, hashVersion || 1);
if (n === null) return false;
return range ? inRange(n, range) : coverage !== undefined ? n <= coverage : true;
}
export function getExperimentResult(ctx, experiment, variationIndex, hashUsed, featureId, bucket, stickyBucketUsed) {
let inExperiment = true;
// If assigned variation is not valid, use the baseline and mark the user as not in the experiment
if (variationIndex < 0 || variationIndex >= experiment.variations.length) {
variationIndex = 0;
inExperiment = false;
}
const {
hashAttribute,
hashValue
} = getHashAttribute(ctx, experiment.hashAttribute, ctx.user.saveStickyBucketAssignmentDoc && !experiment.disableStickyBucketing ? experiment.fallbackAttribute : undefined);
const meta = experiment.meta ? experiment.meta[variationIndex] : {};
const res = {
key: meta.key || "" + variationIndex,
featureId,
inExperiment,
hashUsed,
variationId: variationIndex,
value: experiment.variations[variationIndex],
hashAttribute,
hashValue,
stickyBucketUsed: !!stickyBucketUsed
};
if (meta.name) res.name = meta.name;
if (bucket !== undefined) res.bucket = bucket;
if (meta.passthrough) res.passthrough = meta.passthrough;
return res;
}
function mergeOverrides(experiment, ctx) {
const key = experiment.key;
const o = ctx.global.overrides;
if (o && o[key]) {
experiment = Object.assign({}, experiment, o[key]);
if (typeof experiment.url === "string") {
experiment.url = getUrlRegExp(
// eslint-disable-next-line
experiment.url);
}
}
return experiment;
}
export function getHashAttribute(ctx, attr, fallback) {
let hashAttribute = attr || "id";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let hashValue = "";
const attributes = getAttributes(ctx);
if (attributes[hashAttribute]) {
hashValue = attributes[hashAttribute];
}
// if no match, try fallback
if (!hashValue && fallback) {
if (attributes[fallback]) {
hashValue = attributes[fallback];
}
if (hashValue) {
hashAttribute = fallback;
}
}
return {
hashAttribute,
hashValue
};
}
function urlIsValid(urlRegex, ctx) {
const url = ctx.user.url;
if (!url) return false;
const pathOnly = url.replace(/^https?:\/\//, "").replace(/^[^/]*\//, "/");
if (urlRegex.test(url)) return true;
if (urlRegex.test(pathOnly)) return true;
return false;
}
function hasGroupOverlap(expGroups, ctx) {
const groups = ctx.global.groups || {};
for (let i = 0; i < expGroups.length; i++) {
if (groups[expGroups[i]]) return true;
}
return false;
}
function getStickyBucketVariation(_ref) {
let {
ctx,
expKey,
expBucketVersion,
expHashAttribute,
expFallbackAttribute,
expMinBucketVersion,
expMeta
} = _ref;
expBucketVersion = expBucketVersion || 0;
expMinBucketVersion = expMinBucketVersion || 0;
expHashAttribute = expHashAttribute || "id";
expMeta = expMeta || [];
const id = getStickyBucketExperimentKey(expKey, expBucketVersion);
const assignments = getStickyBucketAssignments(ctx, expHashAttribute, expFallbackAttribute);
// users with any blocked bucket version (0 to minExperimentBucketVersion) are excluded from the test
if (expMinBucketVersion > 0) {
for (let i = 0; i <= expMinBucketVersion; i++) {
const blockedKey = getStickyBucketExperimentKey(expKey, i);
if (assignments[blockedKey] !== undefined) {
return {
variation: -1,
versionIsBlocked: true
};
}
}
}
const variationKey = assignments[id];
if (variationKey === undefined)
// no assignment found
return {
variation: -1
};
const variation = expMeta.findIndex(m => m.key === variationKey);
if (variation < 0)
// invalid assignment, treat as "no assignment found"
return {
variation: -1
};
return {
variation
};
}
function getStickyBucketExperimentKey(experimentKey, experimentBucketVersion) {
experimentBucketVersion = experimentBucketVersion || 0;
return `${experimentKey}__${experimentBucketVersion}`;
}
export function getStickyBucketAttributeKey(attributeName, attributeValue) {
return `${attributeName}||${attributeValue}`;
}
function getStickyBucketAssignments(ctx, expHashAttribute, expFallbackAttribute) {
if (!ctx.user.stickyBucketAssignmentDocs) return {};
const {
hashAttribute,
hashValue
} = getHashAttribute(ctx, expHashAttribute);
const hashKey = getStickyBucketAttributeKey(hashAttribute, toString(hashValue));
const {
hashAttribute: fallbackAttribute,
hashValue: fallbackValue
} = getHashAttribute(ctx, expFallbackAttribute);
const fallbackKey = fallbackValue ? getStickyBucketAttributeKey(fallbackAttribute, toString(fallbackValue)) : null;
const assignments = {};
if (fallbackKey && ctx.user.stickyBucketAssignmentDocs[fallbackKey]) {
Object.assign(assignments, ctx.user.stickyBucketAssignmentDocs[fallbackKey].assignments || {});
}
if (ctx.user.stickyBucketAssignmentDocs[hashKey]) {
Object.assign(assignments, ctx.user.stickyBucketAssignmentDocs[hashKey].assignments || {});
}
return assignments;
}
function generateStickyBucketAssignmentDoc(ctx, attributeName, attributeValue, assignments) {
const key = getStickyBucketAttributeKey(attributeName, attributeValue);
const existingAssignments = ctx.user.stickyBucketAssignmentDocs && ctx.user.stickyBucketAssignmentDocs[key] ? ctx.user.stickyBucketAssignmentDocs[key].assignments || {} : {};
const newAssignments = {
...existingAssignments,
...assignments
};
const changed = JSON.stringify(existingAssignments) !== JSON.stringify(newAssignments);
return {
key,
doc: {
attributeName,
attributeValue,
assignments: newAssignments
},
changed
};
}
function deriveStickyBucketIdentifierAttributes(ctx, data) {
const attributes = new Set();
const features = data && data.features ? data.features : ctx.global.features || {};
const experiments = data && data.experiments ? data.experiments : ctx.global.experiments || [];
Object.keys(features).forEach(id => {
const feature = features[id];
if (feature.rules) {
for (const rule of feature.rules) {
if (rule.variations) {
attributes.add(rule.hashAttribute || "id");
if (rule.fallbackAttribute) {
attributes.add(rule.fallbackAttribute);
}
}
}
}
});
experiments.map(experiment => {
attributes.add(experiment.hashAttribute || "id");
if (experiment.fallbackAttribute) {
attributes.add(experiment.fallbackAttribute);
}
});
return Array.from(attributes);
}
export async function getAllStickyBucketAssignmentDocs(ctx, stickyBucketService, data) {
const attributes = getStickyBucketAttributes(ctx, data);
return stickyBucketService.getAllAssignments(attributes);
}
export function getStickyBucketAttributes(ctx, data) {
const attributes = {};
const stickyBucketIdentifierAttributes = deriveStickyBucketIdentifierAttributes(ctx, data);
stickyBucketIdentifierAttributes.forEach(attr => {
const {
hashValue
} = getHashAttribute(ctx, attr);
attributes[attr] = toString(hashValue);
});
return attributes;
}
export async function decryptPayload(data, decryptionKey, subtle) {
data = {
...data
};
if (data.encryptedFeatures) {
try {
data.features = JSON.parse(await decrypt(data.encryptedFeatures, decryptionKey, subtle));
} catch (e) {
console.error(e);
}
delete data.encryptedFeatures;
}
if (data.encryptedExperiments) {
try {
data.experiments = JSON.parse(await decrypt(data.encryptedExperiments, decryptionKey, subtle));
} catch (e) {
console.error(e);
}
delete data.encryptedExperiments;
}
if (data.encryptedSavedGroups) {
try {
data.savedGroups = JSON.parse(await decrypt(data.encryptedSavedGroups, decryptionKey, subtle));
} catch (e) {
console.error(e);
}
delete data.encryptedSavedGroups;
}
return data;
}
export function getApiHosts(options) {
const defaultHost = options.apiHost || "https://cdn.growthbook.io";
return {
apiHost: defaultHost.replace(/\/*$/, ""),
streamingHost: (options.streamingHost || defaultHost).replace(/\/*$/, ""),
apiRequestHeaders: options.apiHostRequestHeaders,
streamingHostRequestHeaders: options.streamingHostRequestHeaders
};
}
export function getExperimentDedupeKey(experiment, result) {
return result.hashAttribute + result.hashValue + experiment.key + result.variationId;
}
//# sourceMappingURL=core.mjs.map

View File

@@ -0,0 +1,488 @@
import { getPolyfills, promiseTimeout } from "./util.mjs";
// Config settings
const cacheSettings = {
// Consider a fetch stale after 1 minute
staleTTL: 1000 * 60,
// Max time to keep a fetch in cache (4 hours default)
maxAge: 1000 * 60 * 60 * 4,
cacheKey: "gbFeaturesCache",
backgroundSync: true,
maxEntries: 10,
disableIdleStreams: false,
idleStreamInterval: 20000,
disableCache: false
};
const polyfills = getPolyfills();
export const helpers = {
fetchFeaturesCall: _ref => {
let {
host,
clientKey,
headers
} = _ref;
return polyfills.fetch(`${host}/api/features/${clientKey}`, {
headers
});
},
fetchRemoteEvalCall: _ref2 => {
let {
host,
clientKey,
payload,
headers
} = _ref2;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
...headers
},
body: JSON.stringify(payload)
};
return polyfills.fetch(`${host}/api/eval/${clientKey}`, options);
},
eventSourceCall: _ref3 => {
let {
host,
clientKey,
headers
} = _ref3;
if (headers) {
return new polyfills.EventSource(`${host}/sub/${clientKey}`, {
headers
});
}
return new polyfills.EventSource(`${host}/sub/${clientKey}`);
},
startIdleListener: () => {
let idleTimeout;
const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
if (!isBrowser) return;
const onVisibilityChange = () => {
if (document.visibilityState === "visible") {
window.clearTimeout(idleTimeout);
onVisible();
} else if (document.visibilityState === "hidden") {
idleTimeout = window.setTimeout(onHidden, cacheSettings.idleStreamInterval);
}
};
document.addEventListener("visibilitychange", onVisibilityChange);
return () => document.removeEventListener("visibilitychange", onVisibilityChange);
},
stopIdleListener: () => {
// No-op, replaced by startIdleListener
}
};
try {
if (globalThis.localStorage) {
polyfills.localStorage = globalThis.localStorage;
}
} catch (e) {
// Ignore localStorage errors
}
// Global state
const subscribedInstances = new Map();
let cacheInitialized = false;
const cache = new Map();
const activeFetches = new Map();
const streams = new Map();
const supportsSSE = new Set();
// Public functions
export function setPolyfills(overrides) {
Object.assign(polyfills, overrides);
}
export function configureCache(overrides) {
Object.assign(cacheSettings, overrides);
if (!cacheSettings.backgroundSync) {
clearAutoRefresh();
}
}
export async function clearCache() {
cache.clear();
activeFetches.clear();
clearAutoRefresh();
cacheInitialized = false;
await updatePersistentCache();
}
// Get or fetch features and refresh the SDK instance
export async function refreshFeatures(_ref4) {
let {
instance,
timeout,
skipCache,
allowStale,
backgroundSync
} = _ref4;
if (!backgroundSync) {
cacheSettings.backgroundSync = false;
}
return fetchFeaturesWithCache({
instance,
allowStale,
timeout,
skipCache
});
}
// Subscribe a GrowthBook instance to feature changes
function subscribe(instance) {
const key = getKey(instance);
const subs = subscribedInstances.get(key) || new Set();
subs.add(instance);
subscribedInstances.set(key, subs);
}
export function unsubscribe(instance) {
subscribedInstances.forEach(s => s.delete(instance));
}
export function onHidden() {
streams.forEach(channel => {
if (!channel) return;
channel.state = "idle";
disableChannel(channel);
});
}
export function onVisible() {
streams.forEach(channel => {
if (!channel) return;
if (channel.state !== "idle") return;
enableChannel(channel);
});
}
// Private functions
async function updatePersistentCache() {
try {
if (!polyfills.localStorage) return;
await polyfills.localStorage.setItem(cacheSettings.cacheKey, JSON.stringify(Array.from(cache.entries())));
} catch (e) {
// Ignore localStorage errors
}
}
// SWR wrapper for fetching features. May indirectly or directly start SSE streaming.
async function fetchFeaturesWithCache(_ref5) {
let {
instance,
allowStale,
timeout,
skipCache
} = _ref5;
const key = getKey(instance);
const cacheKey = getCacheKey(instance);
const now = new Date();
const minStaleAt = new Date(now.getTime() - cacheSettings.maxAge + cacheSettings.staleTTL);
await initializeCache();
const existing = !cacheSettings.disableCache && !skipCache ? cache.get(cacheKey) : undefined;
if (existing && (allowStale || existing.staleAt > now) && existing.staleAt > minStaleAt) {
// Restore from cache whether SSE is supported
if (existing.sse) supportsSSE.add(key);
// Reload features in the background if stale
if (existing.staleAt < now) {
fetchFeatures(instance);
}
// Otherwise, if we don't need to refresh now, start a background sync
else {
startAutoRefresh(instance);
}
return {
data: existing.data,
success: true,
source: "cache"
};
} else {
const res = await promiseTimeout(fetchFeatures(instance), timeout);
return res || {
data: null,
success: false,
source: "timeout",
error: new Error("Timeout")
};
}
}
function getKey(instance) {
const [apiHost, clientKey] = instance.getApiInfo();
return `${apiHost}||${clientKey}`;
}
function getCacheKey(instance) {
const baseKey = getKey(instance);
if (!("isRemoteEval" in instance) || !instance.isRemoteEval()) return baseKey;
const attributes = instance.getAttributes();
const cacheKeyAttributes = instance.getCacheKeyAttributes() || Object.keys(instance.getAttributes());
const ca = {};
cacheKeyAttributes.forEach(key => {
ca[key] = attributes[key];
});
const fv = instance.getForcedVariations();
const url = instance.getUrl();
return `${baseKey}||${JSON.stringify({
ca,
fv,
url
})}`;
}
// Populate cache from localStorage (if available)
async function initializeCache() {
if (cacheInitialized) return;
cacheInitialized = true;
try {
if (polyfills.localStorage) {
const value = await polyfills.localStorage.getItem(cacheSettings.cacheKey);
if (!cacheSettings.disableCache && value) {
const parsed = JSON.parse(value);
if (parsed && Array.isArray(parsed)) {
parsed.forEach(_ref6 => {
let [key, data] = _ref6;
cache.set(key, {
...data,
staleAt: new Date(data.staleAt)
});
});
}
cleanupCache();
}
}
} catch (e) {
// Ignore localStorage errors
}
if (!cacheSettings.disableIdleStreams) {
const cleanupFn = helpers.startIdleListener();
if (cleanupFn) {
helpers.stopIdleListener = cleanupFn;
}
}
}
// Enforce the maxEntries limit
function cleanupCache() {
const entriesWithTimestamps = Array.from(cache.entries()).map(_ref7 => {
let [key, value] = _ref7;
return {
key,
staleAt: value.staleAt.getTime()
};
}).sort((a, b) => a.staleAt - b.staleAt);
const entriesToRemoveCount = Math.min(Math.max(0, cache.size - cacheSettings.maxEntries), cache.size);
for (let i = 0; i < entriesToRemoveCount; i++) {
cache.delete(entriesWithTimestamps[i].key);
}
}
// Called whenever new features are fetched from the API
function onNewFeatureData(key, cacheKey, data) {
// If contents haven't changed, ignore the update, extend the stale TTL
const version = data.dateUpdated || "";
const staleAt = new Date(Date.now() + cacheSettings.staleTTL);
const existing = !cacheSettings.disableCache ? cache.get(cacheKey) : undefined;
if (existing && version && existing.version === version) {
existing.staleAt = staleAt;
updatePersistentCache();
return;
}
if (!cacheSettings.disableCache) {
// Update in-memory cache
cache.set(cacheKey, {
data,
version,
staleAt,
sse: supportsSSE.has(key)
});
cleanupCache();
}
// Update local storage (don't await this, just update asynchronously)
updatePersistentCache();
// Update features for all subscribed GrowthBook instances
const instances = subscribedInstances.get(key);
instances && instances.forEach(instance => refreshInstance(instance, data));
}
async function refreshInstance(instance, data) {
await instance.setPayload(data || instance.getPayload());
}
// Fetch the features payload from helper function or from in-mem injected payload
async function fetchFeatures(instance) {
const {
apiHost,
apiRequestHeaders
} = instance.getApiHosts();
const clientKey = instance.getClientKey();
const remoteEval = "isRemoteEval" in instance && instance.isRemoteEval();
const key = getKey(instance);
const cacheKey = getCacheKey(instance);
let promise = activeFetches.get(cacheKey);
if (!promise) {
const fetcher = remoteEval ? helpers.fetchRemoteEvalCall({
host: apiHost,
clientKey,
payload: {
attributes: instance.getAttributes(),
forcedVariations: instance.getForcedVariations(),
forcedFeatures: Array.from(instance.getForcedFeatures().entries()),
url: instance.getUrl()
},
headers: apiRequestHeaders
}) : helpers.fetchFeaturesCall({
host: apiHost,
clientKey,
headers: apiRequestHeaders
});
// TODO: auto-retry if status code indicates a temporary error
promise = fetcher.then(res => {
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
if (res.headers.get("x-sse-support") === "enabled") {
supportsSSE.add(key);
}
return res.json();
}).then(data => {
onNewFeatureData(key, cacheKey, data);
startAutoRefresh(instance);
activeFetches.delete(cacheKey);
return {
data,
success: true,
source: "network"
};
}).catch(e => {
process.env.NODE_ENV !== "production" && instance.log("Error fetching features", {
apiHost,
clientKey,
error: e ? e.message : null
});
activeFetches.delete(cacheKey);
return {
data: null,
source: "error",
success: false,
error: e
};
});
activeFetches.set(cacheKey, promise);
}
return promise;
}
// Start SSE streaming, listens to feature payload changes and triggers a refresh or re-fetch
function startAutoRefresh(instance) {
let forceSSE = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const key = getKey(instance);
const cacheKey = getCacheKey(instance);
const {
streamingHost,
streamingHostRequestHeaders
} = instance.getApiHosts();
const clientKey = instance.getClientKey();
if (forceSSE) {
supportsSSE.add(key);
}
if (cacheSettings.backgroundSync && supportsSSE.has(key) && polyfills.EventSource) {
if (streams.has(key)) return;
const channel = {
src: null,
host: streamingHost,
clientKey,
headers: streamingHostRequestHeaders,
cb: event => {
try {
if (event.type === "features-updated") {
const instances = subscribedInstances.get(key);
instances && instances.forEach(instance => {
fetchFeatures(instance);
});
} else if (event.type === "features") {
const json = JSON.parse(event.data);
onNewFeatureData(key, cacheKey, json);
}
// Reset error count on success
channel.errors = 0;
} catch (e) {
process.env.NODE_ENV !== "production" && instance.log("SSE Error", {
streamingHost,
clientKey,
error: e ? e.message : null
});
onSSEError(channel);
}
},
errors: 0,
state: "active"
};
streams.set(key, channel);
enableChannel(channel);
}
}
function onSSEError(channel) {
if (channel.state === "idle") return;
channel.errors++;
if (channel.errors > 3 || channel.src && channel.src.readyState === 2) {
// exponential backoff after 4 errors, with jitter
const delay = Math.pow(3, channel.errors - 3) * (1000 + Math.random() * 1000);
disableChannel(channel);
setTimeout(() => {
if (["idle", "active"].includes(channel.state)) return;
enableChannel(channel);
}, Math.min(delay, 300000)); // 5 minutes max
}
}
function disableChannel(channel) {
if (!channel.src) return;
channel.src.onopen = null;
channel.src.onerror = null;
channel.src.close();
channel.src = null;
if (channel.state === "active") {
channel.state = "disabled";
}
}
function enableChannel(channel) {
channel.src = helpers.eventSourceCall({
host: channel.host,
clientKey: channel.clientKey,
headers: channel.headers
});
channel.state = "active";
channel.src.addEventListener("features", channel.cb);
channel.src.addEventListener("features-updated", channel.cb);
channel.src.onerror = () => onSSEError(channel);
channel.src.onopen = () => {
channel.errors = 0;
};
}
function destroyChannel(channel, key) {
disableChannel(channel);
streams.delete(key);
}
function clearAutoRefresh() {
// Clear list of which keys are auto-updated
supportsSSE.clear();
// Stop listening for any SSE events
streams.forEach(destroyChannel);
// Remove all references to GrowthBook instances
subscribedInstances.clear();
// Run the idle stream cleanup function
helpers.stopIdleListener();
}
export function startStreaming(instance, options) {
if (options.streaming) {
if (!instance.getClientKey()) {
throw new Error("Must specify clientKey to enable streaming");
}
if (options.payload) {
startAutoRefresh(instance, true);
}
subscribe(instance);
}
}
//# sourceMappingURL=feature-repository.mjs.map

View File

@@ -0,0 +1,8 @@
export { setPolyfills, clearCache, configureCache, helpers, onVisible, onHidden } from "./feature-repository.mjs";
export { GrowthBook, prefetchPayload } from "./GrowthBook.mjs";
export { GrowthBookClient as GrowthBookMultiUser, GrowthBookClient, UserScopedGrowthBook } from "./GrowthBookClient.mjs";
export { StickyBucketService, StickyBucketServiceSync, LocalStorageStickyBucketService, ExpressCookieStickyBucketService, BrowserCookieStickyBucketService, RedisStickyBucketService } from "./sticky-bucket-service.mjs";
export { evalCondition } from "./mongrule.mjs";
export { isURLTargeted, getPolyfills, getAutoExperimentChangeType, paddedVersionString } from "./util.mjs";
export { EVENT_EXPERIMENT_VIEWED, EVENT_FEATURE_EVALUATED } from "./core.mjs";
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1,214 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { paddedVersionString } from "./util.mjs";
const _regexCache = {};
// The top-level condition evaluation function
export function evalCondition(obj, condition,
// Must be included for `condition` to correctly evaluate group Operators
savedGroups) {
savedGroups = savedGroups || {};
// Condition is an object, keys are either specific operators or object paths
// values are either arguments for operators or conditions for paths
for (const [k, v] of Object.entries(condition)) {
switch (k) {
case "$or":
if (!evalOr(obj, v, savedGroups)) return false;
break;
case "$nor":
if (evalOr(obj, v, savedGroups)) return false;
break;
case "$and":
if (!evalAnd(obj, v, savedGroups)) return false;
break;
case "$not":
if (evalCondition(obj, v, savedGroups)) return false;
break;
default:
if (!evalConditionValue(v, getPath(obj, k), savedGroups)) return false;
}
}
return true;
}
// Return value at dot-separated path of an object
function getPath(obj, path) {
const parts = path.split(".");
let current = obj;
for (let i = 0; i < parts.length; i++) {
if (current && typeof current === "object" && parts[i] in current) {
current = current[parts[i]];
} else {
return null;
}
}
return current;
}
// Transform a regex string into a real RegExp object
function getRegex(regex) {
if (!_regexCache[regex]) {
_regexCache[regex] = new RegExp(regex.replace(/([^\\])\//g, "$1\\/"));
}
return _regexCache[regex];
}
// Evaluate a single value against a condition
function evalConditionValue(condition, value, savedGroups) {
// Simple equality comparisons
if (typeof condition === "string") {
return value + "" === condition;
}
if (typeof condition === "number") {
return value * 1 === condition;
}
if (typeof condition === "boolean") {
return value !== null && !!value === condition;
}
if (condition === null) {
return value === null;
}
if (Array.isArray(condition) || !isOperatorObject(condition)) {
return JSON.stringify(value) === JSON.stringify(condition);
}
// This is a special operator condition and we should evaluate each one separately
for (const op in condition) {
if (!evalOperatorCondition(op, value, condition[op], savedGroups)) {
return false;
}
}
return true;
}
// If the object has only keys that start with '$'
function isOperatorObject(obj) {
const keys = Object.keys(obj);
return keys.length > 0 && keys.filter(k => k[0] === "$").length === keys.length;
}
// Return the data type of a value
function getType(v) {
if (v === null) return "null";
if (Array.isArray(v)) return "array";
const t = typeof v;
if (["string", "number", "boolean", "object", "undefined"].includes(t)) {
return t;
}
return "unknown";
}
// At least one element of actual must match the expected condition/value
function elemMatch(actual, expected, savedGroups) {
if (!Array.isArray(actual)) return false;
const check = isOperatorObject(expected) ? v => evalConditionValue(expected, v, savedGroups) : v => evalCondition(v, expected, savedGroups);
for (let i = 0; i < actual.length; i++) {
if (actual[i] && check(actual[i])) {
return true;
}
}
return false;
}
function isIn(actual, expected) {
// Do an intersection if attribute is an array
if (Array.isArray(actual)) {
return actual.some(el => expected.includes(el));
}
return expected.includes(actual);
}
// Evaluate a single operator condition
function evalOperatorCondition(operator, actual, expected, savedGroups) {
switch (operator) {
case "$veq":
return paddedVersionString(actual) === paddedVersionString(expected);
case "$vne":
return paddedVersionString(actual) !== paddedVersionString(expected);
case "$vgt":
return paddedVersionString(actual) > paddedVersionString(expected);
case "$vgte":
return paddedVersionString(actual) >= paddedVersionString(expected);
case "$vlt":
return paddedVersionString(actual) < paddedVersionString(expected);
case "$vlte":
return paddedVersionString(actual) <= paddedVersionString(expected);
case "$eq":
return actual === expected;
case "$ne":
return actual !== expected;
case "$lt":
return actual < expected;
case "$lte":
return actual <= expected;
case "$gt":
return actual > expected;
case "$gte":
return actual >= expected;
case "$exists":
// Using `!=` and `==` instead of strict checks so it also matches for undefined
return expected ? actual != null : actual == null;
case "$in":
if (!Array.isArray(expected)) return false;
return isIn(actual, expected);
case "$inGroup":
return isIn(actual, savedGroups[expected] || []);
case "$notInGroup":
return !isIn(actual, savedGroups[expected] || []);
case "$nin":
if (!Array.isArray(expected)) return false;
return !isIn(actual, expected);
case "$not":
return !evalConditionValue(expected, actual, savedGroups);
case "$size":
if (!Array.isArray(actual)) return false;
return evalConditionValue(expected, actual.length, savedGroups);
case "$elemMatch":
return elemMatch(actual, expected, savedGroups);
case "$all":
if (!Array.isArray(actual)) return false;
for (let i = 0; i < expected.length; i++) {
let passed = false;
for (let j = 0; j < actual.length; j++) {
if (evalConditionValue(expected[i], actual[j], savedGroups)) {
passed = true;
break;
}
}
if (!passed) return false;
}
return true;
case "$regex":
try {
return getRegex(expected).test(actual);
} catch (e) {
return false;
}
case "$type":
return getType(actual) === expected;
default:
console.error("Unknown operator: " + operator);
return false;
}
}
// Recursive $or rule
function evalOr(obj, conditions, savedGroups) {
if (!conditions.length) return true;
for (let i = 0; i < conditions.length; i++) {
if (evalCondition(obj, conditions[i], savedGroups)) {
return true;
}
}
return false;
}
// Recursive $and rule
function evalAnd(obj, conditions, savedGroups) {
for (let i = 0; i < conditions.length; i++) {
if (!evalCondition(obj, conditions[i], savedGroups)) {
return false;
}
}
return true;
}
//# sourceMappingURL=mongrule.mjs.map

View File

@@ -0,0 +1,312 @@
const polyfills = {
fetch: globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined,
SubtleCrypto: globalThis.crypto ? globalThis.crypto.subtle : undefined,
EventSource: globalThis.EventSource
};
export function getPolyfills() {
return polyfills;
}
function hashFnv32a(str) {
let hval = 0x811c9dc5;
const l = str.length;
for (let i = 0; i < l; i++) {
hval ^= str.charCodeAt(i);
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
}
return hval >>> 0;
}
export function hash(seed, value, version) {
// New unbiased hashing algorithm
if (version === 2) {
return hashFnv32a(hashFnv32a(seed + value) + "") % 10000 / 10000;
}
// Original biased hashing algorithm (keep for backwards compatibility)
if (version === 1) {
return hashFnv32a(value + seed) % 1000 / 1000;
}
// Unknown hash version
return null;
}
export function getEqualWeights(n) {
if (n <= 0) return [];
return new Array(n).fill(1 / n);
}
export function inRange(n, range) {
return n >= range[0] && n < range[1];
}
export function inNamespace(hashValue, namespace) {
const n = hash("__" + namespace[0], hashValue, 1);
if (n === null) return false;
return n >= namespace[1] && n < namespace[2];
}
export function chooseVariation(n, ranges) {
for (let i = 0; i < ranges.length; i++) {
if (inRange(n, ranges[i])) {
return i;
}
}
return -1;
}
export function getUrlRegExp(regexString) {
try {
const escaped = regexString.replace(/([^\\])\//g, "$1\\/");
return new RegExp(escaped);
} catch (e) {
console.error(e);
return undefined;
}
}
export function isURLTargeted(url, targets) {
if (!targets.length) return false;
let hasIncludeRules = false;
let isIncluded = false;
for (let i = 0; i < targets.length; i++) {
const match = _evalURLTarget(url, targets[i].type, targets[i].pattern);
if (targets[i].include === false) {
if (match) return false;
} else {
hasIncludeRules = true;
if (match) isIncluded = true;
}
}
return isIncluded || !hasIncludeRules;
}
function _evalSimpleUrlPart(actual, pattern, isPath) {
try {
// Escape special regex characters and change wildcard `_____` to `.*`
let escaped = pattern.replace(/[*.+?^${}()|[\]\\]/g, "\\$&").replace(/_____/g, ".*");
if (isPath) {
// When matching pathname, make leading/trailing slashes optional
escaped = "\\/?" + escaped.replace(/(^\/|\/$)/g, "") + "\\/?";
}
const regex = new RegExp("^" + escaped + "$", "i");
return regex.test(actual);
} catch (e) {
return false;
}
}
function _evalSimpleUrlTarget(actual, pattern) {
try {
// If a protocol is missing, but a host is specified, add `https://` to the front
// Use "_____" as the wildcard since `*` is not a valid hostname in some browsers
const expected = new URL(pattern.replace(/^([^:/?]*)\./i, "https://$1.").replace(/\*/g, "_____"), "https://_____");
// Compare each part of the URL separately
const comps = [[actual.host, expected.host, false], [actual.pathname, expected.pathname, true]];
// We only want to compare hashes if it's explicitly being targeted
if (expected.hash) {
comps.push([actual.hash, expected.hash, false]);
}
expected.searchParams.forEach((v, k) => {
comps.push([actual.searchParams.get(k) || "", v, false]);
});
// If any comparisons fail, the whole thing fails
return !comps.some(data => !_evalSimpleUrlPart(data[0], data[1], data[2]));
} catch (e) {
return false;
}
}
function _evalURLTarget(url, type, pattern) {
try {
const parsed = new URL(url, "https://_");
if (type === "regex") {
const regex = getUrlRegExp(pattern);
if (!regex) return false;
return regex.test(parsed.href) || regex.test(parsed.href.substring(parsed.origin.length));
} else if (type === "simple") {
return _evalSimpleUrlTarget(parsed, pattern);
}
return false;
} catch (e) {
return false;
}
}
export function getBucketRanges(numVariations, coverage, weights) {
coverage = coverage === undefined ? 1 : coverage;
// Make sure coverage is within bounds
if (coverage < 0) {
if (process.env.NODE_ENV !== "production") {
console.error("Experiment.coverage must be greater than or equal to 0");
}
coverage = 0;
} else if (coverage > 1) {
if (process.env.NODE_ENV !== "production") {
console.error("Experiment.coverage must be less than or equal to 1");
}
coverage = 1;
}
// Default to equal weights if missing or invalid
const equal = getEqualWeights(numVariations);
weights = weights || equal;
if (weights.length !== numVariations) {
if (process.env.NODE_ENV !== "production") {
console.error("Experiment.weights array must be the same length as Experiment.variations");
}
weights = equal;
}
// If weights don't add up to 1 (or close to it), default to equal weights
const totalWeight = weights.reduce((w, sum) => sum + w, 0);
if (totalWeight < 0.99 || totalWeight > 1.01) {
if (process.env.NODE_ENV !== "production") {
console.error("Experiment.weights must add up to 1");
}
weights = equal;
}
// Covert weights to ranges
let cumulative = 0;
return weights.map(w => {
const start = cumulative;
cumulative += w;
return [start, start + coverage * w];
});
}
export function getQueryStringOverride(id, url, numVariations) {
if (!url) {
return null;
}
const search = url.split("?")[1];
if (!search) {
return null;
}
const match = search.replace(/#.*/, "") // Get rid of anchor
.split("&") // Split into key/value pairs
.map(kv => kv.split("=", 2)).filter(_ref => {
let [k] = _ref;
return k === id;
}) // Look for key that matches the experiment id
.map(_ref2 => {
let [, v] = _ref2;
return parseInt(v);
}); // Parse the value into an integer
if (match.length > 0 && match[0] >= 0 && match[0] < numVariations) return match[0];
return null;
}
export function isIncluded(include) {
try {
return include();
} catch (e) {
console.error(e);
return false;
}
}
const base64ToBuf = b => Uint8Array.from(atob(b), c => c.charCodeAt(0));
export async function decrypt(encryptedString, decryptionKey, subtle) {
decryptionKey = decryptionKey || "";
subtle = subtle || globalThis.crypto && globalThis.crypto.subtle || polyfills.SubtleCrypto;
if (!subtle) {
throw new Error("No SubtleCrypto implementation found");
}
try {
const key = await subtle.importKey("raw", base64ToBuf(decryptionKey), {
name: "AES-CBC",
length: 128
}, true, ["encrypt", "decrypt"]);
const [iv, cipherText] = encryptedString.split(".");
const plainTextBuffer = await subtle.decrypt({
name: "AES-CBC",
iv: base64ToBuf(iv)
}, key, base64ToBuf(cipherText));
return new TextDecoder().decode(plainTextBuffer);
} catch (e) {
throw new Error("Failed to decrypt");
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function toString(input) {
if (typeof input === "string") return input;
return JSON.stringify(input);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function paddedVersionString(input) {
if (typeof input === "number") {
input = input + "";
}
if (!input || typeof input !== "string") {
input = "0";
}
// Remove build info and leading `v` if any
// Split version into parts (both core version numbers and pre-release tags)
// "v1.2.3-rc.1+build123" -> ["1","2","3","rc","1"]
const parts = input.replace(/(^v|\+.*$)/g, "").split(/[-.]/);
// If it's SemVer without a pre-release, add `~` to the end
// ["1","0","0"] -> ["1","0","0","~"]
// "~" is the largest ASCII character, so this will make "1.0.0" greater than "1.0.0-beta" for example
if (parts.length === 3) {
parts.push("~");
}
// Left pad each numeric part with spaces so string comparisons will work ("9">"10", but " 9"<"10")
// Then, join back together into a single string
return parts.map(v => v.match(/^[0-9]+$/) ? v.padStart(5, " ") : v).join("-");
}
export function loadSDKVersion() {
let version;
try {
// @ts-expect-error right-hand value to be replaced by build with string literal
version = "1.6.1";
} catch (e) {
version = "";
}
return version;
}
export function mergeQueryStrings(oldUrl, newUrl) {
let currUrl;
let redirectUrl;
try {
currUrl = new URL(oldUrl);
redirectUrl = new URL(newUrl);
} catch (e) {
console.error(`Unable to merge query strings: ${e}`);
return newUrl;
}
currUrl.searchParams.forEach((value, key) => {
// skip if search param already exists in redirectUrl
if (redirectUrl.searchParams.has(key)) {
return;
}
redirectUrl.searchParams.set(key, value);
});
return redirectUrl.toString();
}
function isObj(x) {
return typeof x === "object" && x !== null;
}
export function getAutoExperimentChangeType(exp) {
if (exp.urlPatterns && exp.variations.some(variation => isObj(variation) && "urlRedirect" in variation)) {
return "redirect";
} else if (exp.variations.some(variation => isObj(variation) && (variation.domMutations || "js" in variation || "css" in variation))) {
return "visual";
}
return "unknown";
}
// Guarantee the promise always resolves within {timeout} ms
// Resolved value will be `null` when there's an error or it takes too long
// Note: The promise will continue running in the background, even if the timeout is hit
export async function promiseTimeout(promise, timeout) {
return new Promise(resolve => {
let resolved = false;
let timer;
const finish = data => {
if (resolved) return;
resolved = true;
timer && clearTimeout(timer);
resolve(data || null);
};
if (timeout) {
timer = setTimeout(() => finish(), timeout);
}
promise.then(data => finish(data)).catch(() => finish());
});
}
//# sourceMappingURL=util.mjs.map

View File

@@ -0,0 +1,900 @@
import pkceChallenge from 'pkce-challenge';
import { LATEST_PROTOCOL_VERSION } from '../types.js';
import { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js';
import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js';
import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js';
import { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js';
export class UnauthorizedError extends Error {
constructor(message) {
super(message ?? 'Unauthorized');
}
}
function isClientAuthMethod(method) {
return ['client_secret_basic', 'client_secret_post', 'none'].includes(method);
}
const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';
const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256';
/**
* Determines the best client authentication method to use based on server support and client configuration.
*
* Priority order (highest to lowest):
* 1. client_secret_basic (if client secret is available)
* 2. client_secret_post (if client secret is available)
* 3. none (for public clients)
*
* @param clientInformation - OAuth client information containing credentials
* @param supportedMethods - Authentication methods supported by the authorization server
* @returns The selected authentication method
*/
export function selectClientAuthMethod(clientInformation, supportedMethods) {
const hasClientSecret = clientInformation.client_secret !== undefined;
// If server doesn't specify supported methods, use RFC 6749 defaults
if (supportedMethods.length === 0) {
return hasClientSecret ? 'client_secret_post' : 'none';
}
// Prefer the method returned by the server during client registration if valid and supported
if ('token_endpoint_auth_method' in clientInformation &&
clientInformation.token_endpoint_auth_method &&
isClientAuthMethod(clientInformation.token_endpoint_auth_method) &&
supportedMethods.includes(clientInformation.token_endpoint_auth_method)) {
return clientInformation.token_endpoint_auth_method;
}
// Try methods in priority order (most secure first)
if (hasClientSecret && supportedMethods.includes('client_secret_basic')) {
return 'client_secret_basic';
}
if (hasClientSecret && supportedMethods.includes('client_secret_post')) {
return 'client_secret_post';
}
if (supportedMethods.includes('none')) {
return 'none';
}
// Fallback: use what we have
return hasClientSecret ? 'client_secret_post' : 'none';
}
/**
* Applies client authentication to the request based on the specified method.
*
* Implements OAuth 2.1 client authentication methods:
* - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
* - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
* - none: Public client authentication (RFC 6749 Section 2.1)
*
* @param method - The authentication method to use
* @param clientInformation - OAuth client information containing credentials
* @param headers - HTTP headers object to modify
* @param params - URL search parameters to modify
* @throws {Error} When required credentials are missing
*/
function applyClientAuthentication(method, clientInformation, headers, params) {
const { client_id, client_secret } = clientInformation;
switch (method) {
case 'client_secret_basic':
applyBasicAuth(client_id, client_secret, headers);
return;
case 'client_secret_post':
applyPostAuth(client_id, client_secret, params);
return;
case 'none':
applyPublicAuth(client_id, params);
return;
default:
throw new Error(`Unsupported client authentication method: ${method}`);
}
}
/**
* Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)
*/
function applyBasicAuth(clientId, clientSecret, headers) {
if (!clientSecret) {
throw new Error('client_secret_basic authentication requires a client_secret');
}
const credentials = btoa(`${clientId}:${clientSecret}`);
headers.set('Authorization', `Basic ${credentials}`);
}
/**
* Applies POST body authentication (RFC 6749 Section 2.3.1)
*/
function applyPostAuth(clientId, clientSecret, params) {
params.set('client_id', clientId);
if (clientSecret) {
params.set('client_secret', clientSecret);
}
}
/**
* Applies public client authentication (RFC 6749 Section 2.1)
*/
function applyPublicAuth(clientId, params) {
params.set('client_id', clientId);
}
/**
* Parses an OAuth error response from a string or Response object.
*
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
* and an instance of the appropriate OAuthError subclass will be returned.
* If parsing fails, it falls back to a generic ServerError that includes
* the response status (if available) and original content.
*
* @param input - A Response object or string containing the error response
* @returns A Promise that resolves to an OAuthError instance
*/
export async function parseErrorResponse(input) {
const statusCode = input instanceof Response ? input.status : undefined;
const body = input instanceof Response ? await input.text() : input;
try {
const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
const { error, error_description, error_uri } = result;
const errorClass = OAUTH_ERRORS[error] || ServerError;
return new errorClass(error_description || '', error_uri);
}
catch (error) {
// Not a valid OAuth error response, but try to inform the user of the raw data anyway
const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`;
return new ServerError(errorMessage);
}
}
/**
* Orchestrates the full auth flow with a server.
*
* This can be used as a single entry point for all authorization functionality,
* instead of linking together the other lower-level functions in this module.
*/
export async function auth(provider, options) {
try {
return await authInternal(provider, options);
}
catch (error) {
// Handle recoverable error types by invalidating credentials and retrying
if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
await provider.invalidateCredentials?.('all');
return await authInternal(provider, options);
}
else if (error instanceof InvalidGrantError) {
await provider.invalidateCredentials?.('tokens');
return await authInternal(provider, options);
}
// Throw otherwise
throw error;
}
}
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
// Check if the provider has cached discovery state to skip discovery
const cachedState = await provider.discoveryState?.();
let resourceMetadata;
let authorizationServerUrl;
let metadata;
// If resourceMetadataUrl is not provided, try to load it from cached state
// This handles browser redirects where the URL was saved before navigation
let effectiveResourceMetadataUrl = resourceMetadataUrl;
if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
}
if (cachedState?.authorizationServerUrl) {
// Restore discovery state from cache
authorizationServerUrl = cachedState.authorizationServerUrl;
resourceMetadata = cachedState.resourceMetadata;
metadata =
cachedState.authorizationServerMetadata ?? (await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn }));
// If resource metadata wasn't cached, try to fetch it for selectResourceURL
if (!resourceMetadata) {
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
}
catch {
// RFC 9728 not available — selectResourceURL will handle undefined
}
}
// Re-save if we enriched the cached state with missing metadata
if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
await provider.saveDiscoveryState?.({
authorizationServerUrl: String(authorizationServerUrl),
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
resourceMetadata,
authorizationServerMetadata: metadata
});
}
}
else {
// Full discovery via RFC 9728
const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
authorizationServerUrl = serverInfo.authorizationServerUrl;
metadata = serverInfo.authorizationServerMetadata;
resourceMetadata = serverInfo.resourceMetadata;
// Persist discovery state for future use
// TODO: resourceMetadataUrl is only populated when explicitly provided via options
// or loaded from cached state. The URL derived internally by
// discoverOAuthProtectedResourceMetadata() is not captured back here.
await provider.saveDiscoveryState?.({
authorizationServerUrl: String(authorizationServerUrl),
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
resourceMetadata,
authorizationServerMetadata: metadata
});
}
const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
// Handle client registration if needed
let clientInformation = await Promise.resolve(provider.clientInformation());
if (!clientInformation) {
if (authorizationCode !== undefined) {
throw new Error('Existing OAuth client information is required when exchanging an authorization code');
}
const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
const clientMetadataUrl = provider.clientMetadataUrl;
if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
}
const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
if (shouldUseUrlBasedClientId) {
// SEP-991: URL-based Client IDs
clientInformation = {
client_id: clientMetadataUrl
};
await provider.saveClientInformation?.(clientInformation);
}
else {
// Fallback to dynamic registration
if (!provider.saveClientInformation) {
throw new Error('OAuth client information must be saveable for dynamic registration');
}
const fullInformation = await registerClient(authorizationServerUrl, {
metadata,
clientMetadata: provider.clientMetadata,
fetchFn
});
await provider.saveClientInformation(fullInformation);
clientInformation = fullInformation;
}
}
// Non-interactive flows (e.g., client_credentials, jwt-bearer) don't need a redirect URL
const nonInteractiveFlow = !provider.redirectUrl;
// Exchange authorization code for tokens, or fetch tokens directly for non-interactive flows
if (authorizationCode !== undefined || nonInteractiveFlow) {
const tokens = await fetchToken(provider, authorizationServerUrl, {
metadata,
resource,
authorizationCode,
fetchFn
});
await provider.saveTokens(tokens);
return 'AUTHORIZED';
}
const tokens = await provider.tokens();
// Handle token refresh or new authorization
if (tokens?.refresh_token) {
try {
// Attempt to refresh the token
const newTokens = await refreshAuthorization(authorizationServerUrl, {
metadata,
clientInformation,
refreshToken: tokens.refresh_token,
resource,
addClientAuthentication: provider.addClientAuthentication,
fetchFn
});
await provider.saveTokens(newTokens);
return 'AUTHORIZED';
}
catch (error) {
// If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry.
if (!(error instanceof OAuthError) || error instanceof ServerError) {
// Could not refresh OAuth tokens
}
else {
// Refresh failed for another reason, re-throw
throw error;
}
}
}
const state = provider.state ? await provider.state() : undefined;
// Start new authorization flow
const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
metadata,
clientInformation,
state,
redirectUrl: provider.redirectUrl,
scope: scope || resourceMetadata?.scopes_supported?.join(' ') || provider.clientMetadata.scope,
resource
});
await provider.saveCodeVerifier(codeVerifier);
await provider.redirectToAuthorization(authorizationUrl);
return 'REDIRECT';
}
/**
* SEP-991: URL-based Client IDs
* Validate that the client_id is a valid URL with https scheme
*/
export function isHttpsUrl(value) {
if (!value)
return false;
try {
const url = new URL(value);
return url.protocol === 'https:' && url.pathname !== '/';
}
catch {
return false;
}
}
export async function selectResourceURL(serverUrl, provider, resourceMetadata) {
const defaultResource = resourceUrlFromServerUrl(serverUrl);
// If provider has custom validation, delegate to it
if (provider.validateResourceURL) {
return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
}
// Only include resource parameter when Protected Resource Metadata is present
if (!resourceMetadata) {
return undefined;
}
// Validate that the metadata's resource is compatible with our request
if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
}
// Prefer the resource from metadata since it's what the server is telling us to request
return new URL(resourceMetadata.resource);
}
/**
* Extract resource_metadata, scope, and error from WWW-Authenticate header.
*/
export function extractWWWAuthenticateParams(res) {
const authenticateHeader = res.headers.get('WWW-Authenticate');
if (!authenticateHeader) {
return {};
}
const [type, scheme] = authenticateHeader.split(' ');
if (type.toLowerCase() !== 'bearer' || !scheme) {
return {};
}
const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined;
let resourceMetadataUrl;
if (resourceMetadataMatch) {
try {
resourceMetadataUrl = new URL(resourceMetadataMatch);
}
catch {
// Ignore invalid URL
}
}
const scope = extractFieldFromWwwAuth(res, 'scope') || undefined;
const error = extractFieldFromWwwAuth(res, 'error') || undefined;
return {
resourceMetadataUrl,
scope,
error
};
}
/**
* Extracts a specific field's value from the WWW-Authenticate header string.
*
* @param response The HTTP response object containing the headers.
* @param fieldName The name of the field to extract (e.g., "realm", "nonce").
* @returns The field value
*/
function extractFieldFromWwwAuth(response, fieldName) {
const wwwAuthHeader = response.headers.get('WWW-Authenticate');
if (!wwwAuthHeader) {
return null;
}
const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
const match = wwwAuthHeader.match(pattern);
if (match) {
// Pattern matches: field_name="value" or field_name=value (unquoted)
return match[1] || match[2];
}
return null;
}
/**
* Extract resource_metadata from response header.
* @deprecated Use `extractWWWAuthenticateParams` instead.
*/
export function extractResourceMetadataUrl(res) {
const authenticateHeader = res.headers.get('WWW-Authenticate');
if (!authenticateHeader) {
return undefined;
}
const [type, scheme] = authenticateHeader.split(' ');
if (type.toLowerCase() !== 'bearer' || !scheme) {
return undefined;
}
const regex = /resource_metadata="([^"]*)"/;
const match = regex.exec(authenticateHeader);
if (!match) {
return undefined;
}
try {
return new URL(match[1]);
}
catch {
return undefined;
}
}
/**
* Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
*
* If the server returns a 404 for the well-known endpoint, this function will
* return `undefined`. Any other errors will be thrown as exceptions.
*/
export async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, {
protocolVersion: opts?.protocolVersion,
metadataUrl: opts?.resourceMetadataUrl
});
if (!response || response.status === 404) {
await response?.body?.cancel();
throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
}
return OAuthProtectedResourceMetadataSchema.parse(await response.json());
}
/**
* Helper function to handle fetch with CORS retry logic
*/
async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
try {
return await fetchFn(url, { headers });
}
catch (error) {
if (error instanceof TypeError) {
if (headers) {
// CORS errors come back as TypeError, retry without headers
return fetchWithCorsRetry(url, undefined, fetchFn);
}
else {
// We're getting CORS errors on retry too, return undefined
return undefined;
}
}
throw error;
}
}
/**
* Constructs the well-known path for auth-related metadata discovery
*/
function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) {
// Strip trailing slash from pathname to avoid double slashes
if (pathname.endsWith('/')) {
pathname = pathname.slice(0, -1);
}
return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
}
/**
* Tries to discover OAuth metadata at a specific URL
*/
async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
const headers = {
'MCP-Protocol-Version': protocolVersion
};
return await fetchWithCorsRetry(url, headers, fetchFn);
}
/**
* Determines if fallback to root discovery should be attempted
*/
function shouldAttemptFallback(response, pathname) {
return !response || (response.status >= 400 && response.status < 500 && pathname !== '/');
}
/**
* Generic function for discovering OAuth metadata with fallback support
*/
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
const issuer = new URL(serverUrl);
const protocolVersion = opts?.protocolVersion ?? LATEST_PROTOCOL_VERSION;
let url;
if (opts?.metadataUrl) {
url = new URL(opts.metadataUrl);
}
else {
// Try path-aware discovery first
const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
url.search = issuer.search;
}
let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
// If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery
if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) {
const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
}
return response;
}
/**
* Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.
*
* If the server returns a 404 for the well-known endpoint, this function will
* return `undefined`. Any other errors will be thrown as exceptions.
*
* @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.
*/
export async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) {
if (typeof issuer === 'string') {
issuer = new URL(issuer);
}
if (!authorizationServerUrl) {
authorizationServerUrl = issuer;
}
if (typeof authorizationServerUrl === 'string') {
authorizationServerUrl = new URL(authorizationServerUrl);
}
protocolVersion ?? (protocolVersion = LATEST_PROTOCOL_VERSION);
const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, {
protocolVersion,
metadataServerUrl: authorizationServerUrl
});
if (!response || response.status === 404) {
await response?.body?.cancel();
return undefined;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);
}
return OAuthMetadataSchema.parse(await response.json());
}
/**
* Builds a list of discovery URLs to try for authorization server metadata.
* URLs are returned in priority order:
* 1. OAuth metadata at the given URL
* 2. OIDC metadata endpoints at the given URL
*/
export function buildDiscoveryUrls(authorizationServerUrl) {
const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl;
const hasPath = url.pathname !== '/';
const urlsToTry = [];
if (!hasPath) {
// Root path: https://example.com/.well-known/oauth-authorization-server
urlsToTry.push({
url: new URL('/.well-known/oauth-authorization-server', url.origin),
type: 'oauth'
});
// OIDC: https://example.com/.well-known/openid-configuration
urlsToTry.push({
url: new URL(`/.well-known/openid-configuration`, url.origin),
type: 'oidc'
});
return urlsToTry;
}
// Strip trailing slash from pathname to avoid double slashes
let pathname = url.pathname;
if (pathname.endsWith('/')) {
pathname = pathname.slice(0, -1);
}
// 1. OAuth metadata at the given URL
// Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1
urlsToTry.push({
url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),
type: 'oauth'
});
// 2. OIDC metadata endpoints
// RFC 8414 style: Insert /.well-known/openid-configuration before the path
urlsToTry.push({
url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
type: 'oidc'
});
// OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path
urlsToTry.push({
url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
type: 'oidc'
});
return urlsToTry;
}
/**
* Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
* and OpenID Connect Discovery 1.0 specifications.
*
* This function implements a fallback strategy for authorization server discovery:
* 1. Attempts RFC 8414 OAuth metadata discovery first
* 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
*
* @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
* protected resource metadata, or the MCP server's URL if the
* metadata was not found.
* @param options - Configuration options
* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
* @returns Promise resolving to authorization server metadata, or undefined if discovery fails
*/
export async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
const headers = {
'MCP-Protocol-Version': protocolVersion,
Accept: 'application/json'
};
// Get the list of URLs to try
const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
// Try each URL in order
for (const { url: endpointUrl, type } of urlsToTry) {
const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
if (!response) {
/**
* CORS error occurred - don't throw as the endpoint may not allow CORS,
* continue trying other possible endpoints
*/
continue;
}
if (!response.ok) {
await response.body?.cancel();
// Continue looking for any 4xx response code.
if (response.status >= 400 && response.status < 500) {
continue; // Try next URL
}
throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`);
}
// Parse and validate based on type
if (type === 'oauth') {
return OAuthMetadataSchema.parse(await response.json());
}
else {
return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
}
}
return undefined;
}
/**
* Discovers the authorization server for an MCP server following
* {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected
* Resource Metadata), with fallback to treating the server URL as the
* authorization server.
*
* This function combines two discovery steps into one call:
* 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the
* authorization server URL (RFC 9728).
* 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).
*
* Use this when you need the authorization server metadata for operations outside the
* {@linkcode auth} orchestrator, such as token refresh or token revocation.
*
* @param serverUrl - The MCP resource server URL
* @param opts - Optional configuration
* @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint
* @param opts.fetchFn - Custom fetch function for HTTP requests
* @returns Authorization server URL, metadata, and resource metadata (if available)
*/
export async function discoverOAuthServerInfo(serverUrl, opts) {
let resourceMetadata;
let authorizationServerUrl;
try {
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
authorizationServerUrl = resourceMetadata.authorization_servers[0];
}
}
catch {
// RFC 9728 not supported -- fall back to treating the server URL as the authorization server
}
// If we don't get a valid authorization server from protected resource metadata,
// fall back to the legacy MCP spec behavior: MCP server base URL acts as the authorization server
if (!authorizationServerUrl) {
authorizationServerUrl = String(new URL('/', serverUrl));
}
const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
return {
authorizationServerUrl,
authorizationServerMetadata,
resourceMetadata
};
}
/**
* Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
*/
export async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
let authorizationUrl;
if (metadata) {
authorizationUrl = new URL(metadata.authorization_endpoint);
if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
}
if (metadata.code_challenge_methods_supported &&
!metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
}
}
else {
authorizationUrl = new URL('/authorize', authorizationServerUrl);
}
// Generate PKCE challenge
const challenge = await pkceChallenge();
const codeVerifier = challenge.code_verifier;
const codeChallenge = challenge.code_challenge;
authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE);
authorizationUrl.searchParams.set('client_id', clientInformation.client_id);
authorizationUrl.searchParams.set('code_challenge', codeChallenge);
authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD);
authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl));
if (state) {
authorizationUrl.searchParams.set('state', state);
}
if (scope) {
authorizationUrl.searchParams.set('scope', scope);
}
if (scope?.includes('offline_access')) {
// if the request includes the OIDC-only "offline_access" scope,
// we need to set the prompt to "consent" to ensure the user is prompted to grant offline access
// https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
authorizationUrl.searchParams.append('prompt', 'consent');
}
if (resource) {
authorizationUrl.searchParams.set('resource', resource.href);
}
return { authorizationUrl, codeVerifier };
}
/**
* Prepares token request parameters for an authorization code exchange.
*
* This is the default implementation used by fetchToken when the provider
* doesn't implement prepareTokenRequest.
*
* @param authorizationCode - The authorization code received from the authorization endpoint
* @param codeVerifier - The PKCE code verifier
* @param redirectUri - The redirect URI used in the authorization request
* @returns URLSearchParams for the authorization_code grant
*/
export function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
return new URLSearchParams({
grant_type: 'authorization_code',
code: authorizationCode,
code_verifier: codeVerifier,
redirect_uri: String(redirectUri)
});
}
/**
* Internal helper to execute a token request with the given parameters.
* Used by exchangeAuthorization, refreshAuthorization, and fetchToken.
*/
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl);
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json'
});
if (resource) {
tokenRequestParams.set('resource', resource.href);
}
if (addClientAuthentication) {
await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
}
else if (clientInformation) {
const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
}
const response = await (fetchFn ?? fetch)(tokenUrl, {
method: 'POST',
headers,
body: tokenRequestParams
});
if (!response.ok) {
throw await parseErrorResponse(response);
}
return OAuthTokensSchema.parse(await response.json());
}
/**
* Exchanges an authorization code for an access token with the given server.
*
* Supports multiple client authentication methods as specified in OAuth 2.1:
* - Automatically selects the best authentication method based on server support
* - Falls back to appropriate defaults when server metadata is unavailable
*
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration object containing client info, auth code, etc.
* @returns Promise resolving to OAuth tokens
* @throws {Error} When token exchange fails or authentication is invalid
*/
export async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) {
const tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri);
return executeTokenRequest(authorizationServerUrl, {
metadata,
tokenRequestParams,
clientInformation,
addClientAuthentication,
resource,
fetchFn
});
}
/**
* Exchange a refresh token for an updated access token.
*
* Supports multiple client authentication methods as specified in OAuth 2.1:
* - Automatically selects the best authentication method based on server support
* - Preserves the original refresh token if a new one is not returned
*
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration object containing client info, refresh token, etc.
* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
* @throws {Error} When token refresh fails or authentication is invalid
*/
export async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
const tokenRequestParams = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken
});
const tokens = await executeTokenRequest(authorizationServerUrl, {
metadata,
tokenRequestParams,
clientInformation,
addClientAuthentication,
resource,
fetchFn
});
// Preserve original refresh token if server didn't return a new one
return { refresh_token: refreshToken, ...tokens };
}
/**
* Unified token fetching that works with any grant type via provider.prepareTokenRequest().
*
* This function provides a single entry point for obtaining tokens regardless of the
* OAuth grant type. The provider's prepareTokenRequest() method determines which grant
* to use and supplies the grant-specific parameters.
*
* @param provider - OAuth client provider that implements prepareTokenRequest()
* @param authorizationServerUrl - The authorization server's base URL
* @param options - Configuration for the token request
* @returns Promise resolving to OAuth tokens
* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
*
* @example
* // Provider for client_credentials:
* class MyProvider implements OAuthClientProvider {
* prepareTokenRequest(scope) {
* const params = new URLSearchParams({ grant_type: 'client_credentials' });
* if (scope) params.set('scope', scope);
* return params;
* }
* // ... other methods
* }
*
* const tokens = await fetchToken(provider, authServerUrl, { metadata });
*/
export async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
const scope = provider.clientMetadata.scope;
// Use provider's prepareTokenRequest if available, otherwise fall back to authorization_code
let tokenRequestParams;
if (provider.prepareTokenRequest) {
tokenRequestParams = await provider.prepareTokenRequest(scope);
}
// Default to authorization_code grant if no custom prepareTokenRequest
if (!tokenRequestParams) {
if (!authorizationCode) {
throw new Error('Either provider.prepareTokenRequest() or authorizationCode is required');
}
if (!provider.redirectUrl) {
throw new Error('redirectUrl is required for authorization_code flow');
}
const codeVerifier = await provider.codeVerifier();
tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
}
const clientInformation = await provider.clientInformation();
return executeTokenRequest(authorizationServerUrl, {
metadata,
tokenRequestParams,
clientInformation: clientInformation ?? undefined,
addClientAuthentication: provider.addClientAuthentication,
resource,
fetchFn
});
}
/**
* Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
*/
export async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) {
let registrationUrl;
if (metadata) {
if (!metadata.registration_endpoint) {
throw new Error('Incompatible auth server: does not support dynamic client registration');
}
registrationUrl = new URL(metadata.registration_endpoint);
}
else {
registrationUrl = new URL('/register', authorizationServerUrl);
}
const response = await (fetchFn ?? fetch)(registrationUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(clientMetadata)
});
if (!response.ok) {
throw await parseErrorResponse(response);
}
return OAuthClientInformationFullSchema.parse(await response.json());
}
//# sourceMappingURL=auth.js.map

View File

@@ -0,0 +1,624 @@
import { mergeCapabilities, Protocol } from '../shared/protocol.js';
import { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';
import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';
import { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js';
import { ExperimentalClientTasks } from '../experimental/tasks/client.js';
import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';
/**
* Elicitation default application helper. Applies defaults to the data based on the schema.
*
* @param schema - The schema to apply defaults to.
* @param data - The data to apply defaults to.
*/
function applyElicitationDefaults(schema, data) {
if (!schema || data === null || typeof data !== 'object')
return;
// Handle object properties
if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {
const obj = data;
const props = schema.properties;
for (const key of Object.keys(props)) {
const propSchema = props[key];
// If missing or explicitly undefined, apply default if present
if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {
obj[key] = propSchema.default;
}
// Recurse into existing nested objects/arrays
if (obj[key] !== undefined) {
applyElicitationDefaults(propSchema, obj[key]);
}
}
}
if (Array.isArray(schema.anyOf)) {
for (const sub of schema.anyOf) {
// Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)
if (typeof sub !== 'boolean') {
applyElicitationDefaults(sub, data);
}
}
}
// Combine schemas
if (Array.isArray(schema.oneOf)) {
for (const sub of schema.oneOf) {
// Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)
if (typeof sub !== 'boolean') {
applyElicitationDefaults(sub, data);
}
}
}
}
/**
* Determines which elicitation modes are supported based on declared client capabilities.
*
* According to the spec:
* - An empty elicitation capability object defaults to form mode support (backwards compatibility)
* - URL mode is only supported if explicitly declared
*
* @param capabilities - The client's elicitation capabilities
* @returns An object indicating which modes are supported
*/
export function getSupportedElicitationModes(capabilities) {
if (!capabilities) {
return { supportsFormMode: false, supportsUrlMode: false };
}
const hasFormCapability = capabilities.form !== undefined;
const hasUrlCapability = capabilities.url !== undefined;
// If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)
const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);
const supportsUrlMode = hasUrlCapability;
return { supportsFormMode, supportsUrlMode };
}
/**
* An MCP client on top of a pluggable transport.
*
* The client will automatically begin the initialization flow with the server when connect() is called.
*
* To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
*
* ```typescript
* // Custom schemas
* const CustomRequestSchema = RequestSchema.extend({...})
* const CustomNotificationSchema = NotificationSchema.extend({...})
* const CustomResultSchema = ResultSchema.extend({...})
*
* // Type aliases
* type CustomRequest = z.infer<typeof CustomRequestSchema>
* type CustomNotification = z.infer<typeof CustomNotificationSchema>
* type CustomResult = z.infer<typeof CustomResultSchema>
*
* // Create typed client
* const client = new Client<CustomRequest, CustomNotification, CustomResult>({
* name: "CustomClient",
* version: "1.0.0"
* })
* ```
*/
export class Client extends Protocol {
/**
* Initializes this client with the given name and version information.
*/
constructor(_clientInfo, options) {
super(options);
this._clientInfo = _clientInfo;
this._cachedToolOutputValidators = new Map();
this._cachedKnownTaskTools = new Set();
this._cachedRequiredTaskTools = new Set();
this._listChangedDebounceTimers = new Map();
this._capabilities = options?.capabilities ?? {};
this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
// Store list changed config for setup after connection (when we know server capabilities)
if (options?.listChanged) {
this._pendingListChangedConfig = options.listChanged;
}
}
/**
* Set up handlers for list changed notifications based on config and server capabilities.
* This should only be called after initialization when server capabilities are known.
* Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
* @internal
*/
_setupListChangedHandlers(config) {
if (config.tools && this._serverCapabilities?.tools?.listChanged) {
this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {
const result = await this.listTools();
return result.tools;
});
}
if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {
const result = await this.listPrompts();
return result.prompts;
});
}
if (config.resources && this._serverCapabilities?.resources?.listChanged) {
this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {
const result = await this.listResources();
return result.resources;
});
}
}
/**
* Access experimental features.
*
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
get experimental() {
if (!this._experimental) {
this._experimental = {
tasks: new ExperimentalClientTasks(this)
};
}
return this._experimental;
}
/**
* Registers new capabilities. This can only be called before connecting to a transport.
*
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
*/
registerCapabilities(capabilities) {
if (this.transport) {
throw new Error('Cannot register capabilities after connecting to transport');
}
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
}
/**
* Override request handler registration to enforce client-side validation for elicitation.
*/
setRequestHandler(requestSchema, handler) {
const shape = getObjectShape(requestSchema);
const methodSchema = shape?.method;
if (!methodSchema) {
throw new Error('Schema is missing a method literal');
}
// Extract literal value using type-safe property access
let methodValue;
if (isZ4Schema(methodSchema)) {
const v4Schema = methodSchema;
const v4Def = v4Schema._zod?.def;
methodValue = v4Def?.value ?? v4Schema.value;
}
else {
const v3Schema = methodSchema;
const legacyDef = v3Schema._def;
methodValue = legacyDef?.value ?? v3Schema.value;
}
if (typeof methodValue !== 'string') {
throw new Error('Schema method literal must be a string');
}
const method = methodValue;
if (method === 'elicitation/create') {
const wrappedHandler = async (request, extra) => {
const validatedRequest = safeParse(ElicitRequestSchema, request);
if (!validatedRequest.success) {
// Type guard: if success is false, error is guaranteed to exist
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
}
const { params } = validatedRequest.data;
params.mode = params.mode ?? 'form';
const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
if (params.mode === 'form' && !supportsFormMode) {
throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');
}
if (params.mode === 'url' && !supportsUrlMode) {
throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');
}
const result = await Promise.resolve(handler(request, extra));
// When task creation is requested, validate and return CreateTaskResult
if (params.task) {
const taskValidationResult = safeParse(CreateTaskResultSchema, result);
if (!taskValidationResult.success) {
const errorMessage = taskValidationResult.error instanceof Error
? taskValidationResult.error.message
: String(taskValidationResult.error);
throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
}
return taskValidationResult.data;
}
// For non-task requests, validate against ElicitResultSchema
const validationResult = safeParse(ElicitResultSchema, result);
if (!validationResult.success) {
// Type guard: if success is false, error is guaranteed to exist
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
}
const validatedResult = validationResult.data;
const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;
if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {
if (this._capabilities.elicitation?.form?.applyDefaults) {
try {
applyElicitationDefaults(requestedSchema, validatedResult.content);
}
catch {
// gracefully ignore errors in default application
}
}
}
return validatedResult;
};
// Install the wrapped handler
return super.setRequestHandler(requestSchema, wrappedHandler);
}
if (method === 'sampling/createMessage') {
const wrappedHandler = async (request, extra) => {
const validatedRequest = safeParse(CreateMessageRequestSchema, request);
if (!validatedRequest.success) {
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
}
const { params } = validatedRequest.data;
const result = await Promise.resolve(handler(request, extra));
// When task creation is requested, validate and return CreateTaskResult
if (params.task) {
const taskValidationResult = safeParse(CreateTaskResultSchema, result);
if (!taskValidationResult.success) {
const errorMessage = taskValidationResult.error instanceof Error
? taskValidationResult.error.message
: String(taskValidationResult.error);
throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
}
return taskValidationResult.data;
}
// For non-task requests, validate against appropriate schema based on tools presence
const hasTools = params.tools || params.toolChoice;
const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
const validationResult = safeParse(resultSchema, result);
if (!validationResult.success) {
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
}
return validationResult.data;
};
// Install the wrapped handler
return super.setRequestHandler(requestSchema, wrappedHandler);
}
// Other handlers use default behavior
return super.setRequestHandler(requestSchema, handler);
}
assertCapability(capability, method) {
if (!this._serverCapabilities?.[capability]) {
throw new Error(`Server does not support ${capability} (required for ${method})`);
}
}
async connect(transport, options) {
await super.connect(transport);
// When transport sessionId is already set this means we are trying to reconnect.
// In this case we don't need to initialize again.
if (transport.sessionId !== undefined) {
return;
}
try {
const result = await this.request({
method: 'initialize',
params: {
protocolVersion: LATEST_PROTOCOL_VERSION,
capabilities: this._capabilities,
clientInfo: this._clientInfo
}
}, InitializeResultSchema, options);
if (result === undefined) {
throw new Error(`Server sent invalid initialize result: ${result}`);
}
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
}
this._serverCapabilities = result.capabilities;
this._serverVersion = result.serverInfo;
// HTTP transports must set the protocol version in each header after initialization.
if (transport.setProtocolVersion) {
transport.setProtocolVersion(result.protocolVersion);
}
this._instructions = result.instructions;
await this.notification({
method: 'notifications/initialized'
});
// Set up list changed handlers now that we know server capabilities
if (this._pendingListChangedConfig) {
this._setupListChangedHandlers(this._pendingListChangedConfig);
this._pendingListChangedConfig = undefined;
}
}
catch (error) {
// Disconnect if initialization fails.
void this.close();
throw error;
}
}
/**
* After initialization has completed, this will be populated with the server's reported capabilities.
*/
getServerCapabilities() {
return this._serverCapabilities;
}
/**
* After initialization has completed, this will be populated with information about the server's name and version.
*/
getServerVersion() {
return this._serverVersion;
}
/**
* After initialization has completed, this may be populated with information about the server's instructions.
*/
getInstructions() {
return this._instructions;
}
assertCapabilityForMethod(method) {
switch (method) {
case 'logging/setLevel':
if (!this._serverCapabilities?.logging) {
throw new Error(`Server does not support logging (required for ${method})`);
}
break;
case 'prompts/get':
case 'prompts/list':
if (!this._serverCapabilities?.prompts) {
throw new Error(`Server does not support prompts (required for ${method})`);
}
break;
case 'resources/list':
case 'resources/templates/list':
case 'resources/read':
case 'resources/subscribe':
case 'resources/unsubscribe':
if (!this._serverCapabilities?.resources) {
throw new Error(`Server does not support resources (required for ${method})`);
}
if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {
throw new Error(`Server does not support resource subscriptions (required for ${method})`);
}
break;
case 'tools/call':
case 'tools/list':
if (!this._serverCapabilities?.tools) {
throw new Error(`Server does not support tools (required for ${method})`);
}
break;
case 'completion/complete':
if (!this._serverCapabilities?.completions) {
throw new Error(`Server does not support completions (required for ${method})`);
}
break;
case 'initialize':
// No specific capability required for initialize
break;
case 'ping':
// No specific capability required for ping
break;
}
}
assertNotificationCapability(method) {
switch (method) {
case 'notifications/roots/list_changed':
if (!this._capabilities.roots?.listChanged) {
throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
}
break;
case 'notifications/initialized':
// No specific capability required for initialized
break;
case 'notifications/cancelled':
// Cancellation notifications are always allowed
break;
case 'notifications/progress':
// Progress notifications are always allowed
break;
}
}
assertRequestHandlerCapability(method) {
// Task handlers are registered in Protocol constructor before _capabilities is initialized
// Skip capability check for task methods during initialization
if (!this._capabilities) {
return;
}
switch (method) {
case 'sampling/createMessage':
if (!this._capabilities.sampling) {
throw new Error(`Client does not support sampling capability (required for ${method})`);
}
break;
case 'elicitation/create':
if (!this._capabilities.elicitation) {
throw new Error(`Client does not support elicitation capability (required for ${method})`);
}
break;
case 'roots/list':
if (!this._capabilities.roots) {
throw new Error(`Client does not support roots capability (required for ${method})`);
}
break;
case 'tasks/get':
case 'tasks/list':
case 'tasks/result':
case 'tasks/cancel':
if (!this._capabilities.tasks) {
throw new Error(`Client does not support tasks capability (required for ${method})`);
}
break;
case 'ping':
// No specific capability required for ping
break;
}
}
assertTaskCapability(method) {
assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');
}
assertTaskHandlerCapability(method) {
// Task handlers are registered in Protocol constructor before _capabilities is initialized
// Skip capability check for task methods during initialization
if (!this._capabilities) {
return;
}
assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');
}
async ping(options) {
return this.request({ method: 'ping' }, EmptyResultSchema, options);
}
async complete(params, options) {
return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);
}
async setLoggingLevel(level, options) {
return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);
}
async getPrompt(params, options) {
return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);
}
async listPrompts(params, options) {
return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);
}
async listResources(params, options) {
return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);
}
async listResourceTemplates(params, options) {
return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);
}
async readResource(params, options) {
return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);
}
async subscribeResource(params, options) {
return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);
}
async unsubscribeResource(params, options) {
return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);
}
/**
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
*
* For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
*/
async callTool(params, resultSchema = CallToolResultSchema, options) {
// Guard: required-task tools need experimental API
if (this.isToolTaskRequired(params.name)) {
throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
}
const result = await this.request({ method: 'tools/call', params }, resultSchema, options);
// Check if the tool has an outputSchema
const validator = this.getToolOutputValidator(params.name);
if (validator) {
// If tool has outputSchema, it MUST return structuredContent (unless it's an error)
if (!result.structuredContent && !result.isError) {
throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
}
// Only validate structured content if present (not when there's an error)
if (result.structuredContent) {
try {
// Validate the structured content against the schema
const validationResult = validator(result.structuredContent);
if (!validationResult.valid) {
throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
}
}
catch (error) {
if (error instanceof McpError) {
throw error;
}
throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
return result;
}
isToolTask(toolName) {
if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
return false;
}
return this._cachedKnownTaskTools.has(toolName);
}
/**
* Check if a tool requires task-based execution.
* Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
*/
isToolTaskRequired(toolName) {
return this._cachedRequiredTaskTools.has(toolName);
}
/**
* Cache validators for tool output schemas.
* Called after listTools() to pre-compile validators for better performance.
*/
cacheToolMetadata(tools) {
this._cachedToolOutputValidators.clear();
this._cachedKnownTaskTools.clear();
this._cachedRequiredTaskTools.clear();
for (const tool of tools) {
// If the tool has an outputSchema, create and cache the validator
if (tool.outputSchema) {
const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
this._cachedToolOutputValidators.set(tool.name, toolValidator);
}
// If the tool supports task-based execution, cache that information
const taskSupport = tool.execution?.taskSupport;
if (taskSupport === 'required' || taskSupport === 'optional') {
this._cachedKnownTaskTools.add(tool.name);
}
if (taskSupport === 'required') {
this._cachedRequiredTaskTools.add(tool.name);
}
}
}
/**
* Get cached validator for a tool
*/
getToolOutputValidator(toolName) {
return this._cachedToolOutputValidators.get(toolName);
}
async listTools(params, options) {
const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);
// Cache the tools and their output schemas for future validation
this.cacheToolMetadata(result.tools);
return result;
}
/**
* Set up a single list changed handler.
* @internal
*/
_setupListChangedHandler(listType, notificationSchema, options, fetcher) {
// Validate options using Zod schema (validates autoRefresh and debounceMs)
const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
if (!parseResult.success) {
throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
}
// Validate callback
if (typeof options.onChanged !== 'function') {
throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
}
const { autoRefresh, debounceMs } = parseResult.data;
const { onChanged } = options;
const refresh = async () => {
if (!autoRefresh) {
onChanged(null, null);
return;
}
try {
const items = await fetcher();
onChanged(null, items);
}
catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
onChanged(error, null);
}
};
const handler = () => {
if (debounceMs) {
// Clear any pending debounce timer for this list type
const existingTimer = this._listChangedDebounceTimers.get(listType);
if (existingTimer) {
clearTimeout(existingTimer);
}
// Set up debounced refresh
const timer = setTimeout(refresh, debounceMs);
this._listChangedDebounceTimers.set(listType, timer);
}
else {
// No debounce, refresh immediately
refresh();
}
};
// Register notification handler
this.setNotificationHandler(notificationSchema, handler);
}
async sendRootsListChanged() {
return this.notification({ method: 'notifications/roots/list_changed' });
}
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,206 @@
import { EventSource } from 'eventsource';
import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';
import { JSONRPCMessageSchema } from '../types.js';
import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';
export class SseError extends Error {
constructor(code, message, event) {
super(`SSE error: ${message}`);
this.code = code;
this.event = event;
}
}
/**
* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
* messages and make separate POST requests for sending messages.
* @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
*/
export class SSEClientTransport {
constructor(url, opts) {
this._url = url;
this._resourceMetadataUrl = undefined;
this._scope = undefined;
this._eventSourceInit = opts?.eventSourceInit;
this._requestInit = opts?.requestInit;
this._authProvider = opts?.authProvider;
this._fetch = opts?.fetch;
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
}
async _authThenStart() {
if (!this._authProvider) {
throw new UnauthorizedError('No auth provider');
}
let result;
try {
result = await auth(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
}
catch (error) {
this.onerror?.(error);
throw error;
}
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError();
}
return await this._startOrAuth();
}
async _commonHeaders() {
const headers = {};
if (this._authProvider) {
const tokens = await this._authProvider.tokens();
if (tokens) {
headers['Authorization'] = `Bearer ${tokens.access_token}`;
}
}
if (this._protocolVersion) {
headers['mcp-protocol-version'] = this._protocolVersion;
}
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
return new Headers({
...headers,
...extraHeaders
});
}
_startOrAuth() {
const fetchImpl = (this?._eventSourceInit?.fetch ?? this._fetch ?? fetch);
return new Promise((resolve, reject) => {
this._eventSource = new EventSource(this._url.href, {
...this._eventSourceInit,
fetch: async (url, init) => {
const headers = await this._commonHeaders();
headers.set('Accept', 'text/event-stream');
const response = await fetchImpl(url, {
...init,
headers
});
if (response.status === 401 && response.headers.has('www-authenticate')) {
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
this._resourceMetadataUrl = resourceMetadataUrl;
this._scope = scope;
}
return response;
}
});
this._abortController = new AbortController();
this._eventSource.onerror = event => {
if (event.code === 401 && this._authProvider) {
this._authThenStart().then(resolve, reject);
return;
}
const error = new SseError(event.code, event.message, event);
reject(error);
this.onerror?.(error);
};
this._eventSource.onopen = () => {
// The connection is open, but we need to wait for the endpoint to be received.
};
this._eventSource.addEventListener('endpoint', (event) => {
const messageEvent = event;
try {
this._endpoint = new URL(messageEvent.data, this._url);
if (this._endpoint.origin !== this._url.origin) {
throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
}
}
catch (error) {
reject(error);
this.onerror?.(error);
void this.close();
return;
}
resolve();
});
this._eventSource.onmessage = (event) => {
const messageEvent = event;
let message;
try {
message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
}
catch (error) {
this.onerror?.(error);
return;
}
this.onmessage?.(message);
};
});
}
async start() {
if (this._eventSource) {
throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
return await this._startOrAuth();
}
/**
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
*/
async finishAuth(authorizationCode) {
if (!this._authProvider) {
throw new UnauthorizedError('No auth provider');
}
const result = await auth(this._authProvider, {
serverUrl: this._url,
authorizationCode,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError('Failed to authorize');
}
}
async close() {
this._abortController?.abort();
this._eventSource?.close();
this.onclose?.();
}
async send(message) {
if (!this._endpoint) {
throw new Error('Not connected');
}
try {
const headers = await this._commonHeaders();
headers.set('content-type', 'application/json');
const init = {
...this._requestInit,
method: 'POST',
headers,
body: JSON.stringify(message),
signal: this._abortController?.signal
};
const response = await (this._fetch ?? fetch)(this._endpoint, init);
if (!response.ok) {
const text = await response.text().catch(() => null);
if (response.status === 401 && this._authProvider) {
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
this._resourceMetadataUrl = resourceMetadataUrl;
this._scope = scope;
const result = await auth(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError();
}
// Purposely _not_ awaited, so we don't call onerror twice
return this.send(message);
}
throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
}
// Release connection - POST responses don't have content we need
await response.body?.cancel();
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
setProtocolVersion(version) {
this._protocolVersion = version;
}
}
//# sourceMappingURL=sse.js.map

View File

@@ -0,0 +1,191 @@
import spawn from 'cross-spawn';
import process from 'node:process';
import { PassThrough } from 'node:stream';
import { ReadBuffer, serializeMessage } from '../shared/stdio.js';
/**
* Environment variables to inherit by default, if an environment is not explicitly given.
*/
export const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32'
? [
'APPDATA',
'HOMEDRIVE',
'HOMEPATH',
'LOCALAPPDATA',
'PATH',
'PROCESSOR_ARCHITECTURE',
'SYSTEMDRIVE',
'SYSTEMROOT',
'TEMP',
'USERNAME',
'USERPROFILE',
'PROGRAMFILES'
]
: /* list inspired by the default env inheritance of sudo */
['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER'];
/**
* Returns a default environment object including only environment variables deemed safe to inherit.
*/
export function getDefaultEnvironment() {
const env = {};
for (const key of DEFAULT_INHERITED_ENV_VARS) {
const value = process.env[key];
if (value === undefined) {
continue;
}
if (value.startsWith('()')) {
// Skip functions, which are a security risk.
continue;
}
env[key] = value;
}
return env;
}
/**
* Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout.
*
* This transport is only available in Node.js environments.
*/
export class StdioClientTransport {
constructor(server) {
this._readBuffer = new ReadBuffer();
this._stderrStream = null;
this._serverParams = server;
if (server.stderr === 'pipe' || server.stderr === 'overlapped') {
this._stderrStream = new PassThrough();
}
}
/**
* Starts the server process and prepares to communicate with it.
*/
async start() {
if (this._process) {
throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
return new Promise((resolve, reject) => {
this._process = spawn(this._serverParams.command, this._serverParams.args ?? [], {
// merge default env with server env because mcp server needs some env vars
env: {
...getDefaultEnvironment(),
...this._serverParams.env
},
stdio: ['pipe', 'pipe', this._serverParams.stderr ?? 'inherit'],
shell: false,
windowsHide: process.platform === 'win32' && isElectron(),
cwd: this._serverParams.cwd
});
this._process.on('error', error => {
reject(error);
this.onerror?.(error);
});
this._process.on('spawn', () => {
resolve();
});
this._process.on('close', _code => {
this._process = undefined;
this.onclose?.();
});
this._process.stdin?.on('error', error => {
this.onerror?.(error);
});
this._process.stdout?.on('data', chunk => {
this._readBuffer.append(chunk);
this.processReadBuffer();
});
this._process.stdout?.on('error', error => {
this.onerror?.(error);
});
if (this._stderrStream && this._process.stderr) {
this._process.stderr.pipe(this._stderrStream);
}
});
}
/**
* The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
*
* If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
* attach listeners before the start method is invoked. This prevents loss of any early
* error output emitted by the child process.
*/
get stderr() {
if (this._stderrStream) {
return this._stderrStream;
}
return this._process?.stderr ?? null;
}
/**
* The child process pid spawned by this transport.
*
* This is only available after the transport has been started.
*/
get pid() {
return this._process?.pid ?? null;
}
processReadBuffer() {
while (true) {
try {
const message = this._readBuffer.readMessage();
if (message === null) {
break;
}
this.onmessage?.(message);
}
catch (error) {
this.onerror?.(error);
}
}
}
async close() {
if (this._process) {
const processToClose = this._process;
this._process = undefined;
const closePromise = new Promise(resolve => {
processToClose.once('close', () => {
resolve();
});
});
try {
processToClose.stdin?.end();
}
catch {
// ignore
}
await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
if (processToClose.exitCode === null) {
try {
processToClose.kill('SIGTERM');
}
catch {
// ignore
}
await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
}
if (processToClose.exitCode === null) {
try {
processToClose.kill('SIGKILL');
}
catch {
// ignore
}
}
}
this._readBuffer.clear();
}
send(message) {
return new Promise(resolve => {
if (!this._process?.stdin) {
throw new Error('Not connected');
}
const json = serializeMessage(message);
if (this._process.stdin.write(json)) {
resolve();
}
else {
this._process.stdin.once('drain', resolve);
}
});
}
}
function isElectron() {
return 'type' in process;
}
//# sourceMappingURL=stdio.js.map

View File

@@ -0,0 +1,477 @@
import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js';
import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema } from '../types.js';
import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';
import { EventSourceParserStream } from 'eventsource-parser/stream';
// Default reconnection options for StreamableHTTP connections
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
initialReconnectionDelay: 1000,
maxReconnectionDelay: 30000,
reconnectionDelayGrowFactor: 1.5,
maxRetries: 2
};
export class StreamableHTTPError extends Error {
constructor(code, message) {
super(`Streamable HTTP error: ${message}`);
this.code = code;
}
}
/**
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
* for receiving messages.
*/
export class StreamableHTTPClientTransport {
constructor(url, opts) {
this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401
this._url = url;
this._resourceMetadataUrl = undefined;
this._scope = undefined;
this._requestInit = opts?.requestInit;
this._authProvider = opts?.authProvider;
this._fetch = opts?.fetch;
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
this._sessionId = opts?.sessionId;
this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
}
async _authThenStart() {
if (!this._authProvider) {
throw new UnauthorizedError('No auth provider');
}
let result;
try {
result = await auth(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
}
catch (error) {
this.onerror?.(error);
throw error;
}
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError();
}
return await this._startOrAuthSse({ resumptionToken: undefined });
}
async _commonHeaders() {
const headers = {};
if (this._authProvider) {
const tokens = await this._authProvider.tokens();
if (tokens) {
headers['Authorization'] = `Bearer ${tokens.access_token}`;
}
}
if (this._sessionId) {
headers['mcp-session-id'] = this._sessionId;
}
if (this._protocolVersion) {
headers['mcp-protocol-version'] = this._protocolVersion;
}
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
return new Headers({
...headers,
...extraHeaders
});
}
async _startOrAuthSse(options) {
const { resumptionToken } = options;
try {
// Try to open an initial SSE stream with GET to listen for server messages
// This is optional according to the spec - server may not support it
const headers = await this._commonHeaders();
headers.set('Accept', 'text/event-stream');
// Include Last-Event-ID header for resumable streams if provided
if (resumptionToken) {
headers.set('last-event-id', resumptionToken);
}
const response = await (this._fetch ?? fetch)(this._url, {
method: 'GET',
headers,
signal: this._abortController?.signal
});
if (!response.ok) {
await response.body?.cancel();
if (response.status === 401 && this._authProvider) {
// Need to authenticate
return await this._authThenStart();
}
// 405 indicates that the server does not offer an SSE stream at GET endpoint
// This is an expected case that should not trigger an error
if (response.status === 405) {
return;
}
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
}
this._handleSseStream(response.body, options, true);
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
/**
* Calculates the next reconnection delay using backoff algorithm
*
* @param attempt Current reconnection attempt count for the specific stream
* @returns Time to wait in milliseconds before next reconnection attempt
*/
_getNextReconnectionDelay(attempt) {
// Use server-provided retry value if available
if (this._serverRetryMs !== undefined) {
return this._serverRetryMs;
}
// Fall back to exponential backoff
const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
// Cap at maximum delay
return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
}
/**
* Schedule a reconnection attempt using server-provided retry interval or backoff
*
* @param lastEventId The ID of the last received event for resumability
* @param attemptCount Current reconnection attempt count for this specific stream
*/
_scheduleReconnection(options, attemptCount = 0) {
// Use provided options or default options
const maxRetries = this._reconnectionOptions.maxRetries;
// Check if we've exceeded maximum retry attempts
if (attemptCount >= maxRetries) {
this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
return;
}
// Calculate next delay based on current attempt count
const delay = this._getNextReconnectionDelay(attemptCount);
// Schedule the reconnection
this._reconnectionTimeout = setTimeout(() => {
// Use the last event ID to resume where we left off
this._startOrAuthSse(options).catch(error => {
this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
// Schedule another attempt if this one failed, incrementing the attempt counter
this._scheduleReconnection(options, attemptCount + 1);
});
}, delay);
}
_handleSseStream(stream, options, isReconnectable) {
if (!stream) {
return;
}
const { onresumptiontoken, replayMessageId } = options;
let lastEventId;
// Track whether we've received a priming event (event with ID)
// Per spec, server SHOULD send a priming event with ID before closing
let hasPrimingEvent = false;
// Track whether we've received a response - if so, no need to reconnect
// Reconnection is for when server disconnects BEFORE sending response
let receivedResponse = false;
const processStream = async () => {
// this is the closest we can get to trying to catch network errors
// if something happens reader will throw
try {
// Create a pipeline: binary stream -> text decoder -> SSE parser
const reader = stream
.pipeThrough(new TextDecoderStream())
.pipeThrough(new EventSourceParserStream({
onRetry: (retryMs) => {
// Capture server-provided retry value for reconnection timing
this._serverRetryMs = retryMs;
}
}))
.getReader();
while (true) {
const { value: event, done } = await reader.read();
if (done) {
break;
}
// Update last event ID if provided
if (event.id) {
lastEventId = event.id;
// Mark that we've received a priming event - stream is now resumable
hasPrimingEvent = true;
onresumptiontoken?.(event.id);
}
// Skip events with no data (priming events, keep-alives)
if (!event.data) {
continue;
}
if (!event.event || event.event === 'message') {
try {
const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
if (isJSONRPCResultResponse(message)) {
// Mark that we received a response - no need to reconnect for this request
receivedResponse = true;
if (replayMessageId !== undefined) {
message.id = replayMessageId;
}
}
this.onmessage?.(message);
}
catch (error) {
this.onerror?.(error);
}
}
}
// Handle graceful server-side disconnect
// Server may close connection after sending event ID and retry field
// Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)
// BUT don't reconnect if we already received a response - the request is complete
const canResume = isReconnectable || hasPrimingEvent;
const needsReconnect = canResume && !receivedResponse;
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
this._scheduleReconnection({
resumptionToken: lastEventId,
onresumptiontoken,
replayMessageId
}, 0);
}
}
catch (error) {
// Handle stream errors - likely a network disconnect
this.onerror?.(new Error(`SSE stream disconnected: ${error}`));
// Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing
// Reconnect if: already reconnectable (GET stream) OR received a priming event (POST stream with event ID)
// BUT don't reconnect if we already received a response - the request is complete
const canResume = isReconnectable || hasPrimingEvent;
const needsReconnect = canResume && !receivedResponse;
if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
// Use the exponential backoff reconnection strategy
try {
this._scheduleReconnection({
resumptionToken: lastEventId,
onresumptiontoken,
replayMessageId
}, 0);
}
catch (error) {
this.onerror?.(new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));
}
}
}
};
processStream();
}
async start() {
if (this._abortController) {
throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.');
}
this._abortController = new AbortController();
}
/**
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
*/
async finishAuth(authorizationCode) {
if (!this._authProvider) {
throw new UnauthorizedError('No auth provider');
}
const result = await auth(this._authProvider, {
serverUrl: this._url,
authorizationCode,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError('Failed to authorize');
}
}
async close() {
if (this._reconnectionTimeout) {
clearTimeout(this._reconnectionTimeout);
this._reconnectionTimeout = undefined;
}
this._abortController?.abort();
this.onclose?.();
}
async send(message, options) {
try {
const { resumptionToken, onresumptiontoken } = options || {};
if (resumptionToken) {
// If we have at last event ID, we need to reconnect the SSE stream
this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => this.onerror?.(err));
return;
}
const headers = await this._commonHeaders();
headers.set('content-type', 'application/json');
headers.set('accept', 'application/json, text/event-stream');
const init = {
...this._requestInit,
method: 'POST',
headers,
body: JSON.stringify(message),
signal: this._abortController?.signal
};
const response = await (this._fetch ?? fetch)(this._url, init);
// Handle session ID received during initialization
const sessionId = response.headers.get('mcp-session-id');
if (sessionId) {
this._sessionId = sessionId;
}
if (!response.ok) {
const text = await response.text().catch(() => null);
if (response.status === 401 && this._authProvider) {
// Prevent infinite recursion when server returns 401 after successful auth
if (this._hasCompletedAuthFlow) {
throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication');
}
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
this._resourceMetadataUrl = resourceMetadataUrl;
this._scope = scope;
const result = await auth(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetchWithInit
});
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError();
}
// Mark that we completed auth flow
this._hasCompletedAuthFlow = true;
// Purposely _not_ awaited, so we don't call onerror twice
return this.send(message);
}
if (response.status === 403 && this._authProvider) {
const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
if (error === 'insufficient_scope') {
const wwwAuthHeader = response.headers.get('WWW-Authenticate');
// Check if we've already tried upscoping with this header to prevent infinite loops.
if (this._lastUpscopingHeader === wwwAuthHeader) {
throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping');
}
if (scope) {
this._scope = scope;
}
if (resourceMetadataUrl) {
this._resourceMetadataUrl = resourceMetadataUrl;
}
// Mark that upscoping was tried.
this._lastUpscopingHeader = wwwAuthHeader ?? undefined;
const result = await auth(this._authProvider, {
serverUrl: this._url,
resourceMetadataUrl: this._resourceMetadataUrl,
scope: this._scope,
fetchFn: this._fetch
});
if (result !== 'AUTHORIZED') {
throw new UnauthorizedError();
}
return this.send(message);
}
}
throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
}
// Reset auth loop flag on successful response
this._hasCompletedAuthFlow = false;
this._lastUpscopingHeader = undefined;
// If the response is 202 Accepted, there's no body to process
if (response.status === 202) {
await response.body?.cancel();
// if the accepted notification is initialized, we start the SSE stream
// if it's supported by the server
if (isInitializedNotification(message)) {
// Start without a lastEventId since this is a fresh connection
this._startOrAuthSse({ resumptionToken: undefined }).catch(err => this.onerror?.(err));
}
return;
}
// Get original message(s) for detecting request IDs
const messages = Array.isArray(message) ? message : [message];
const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0;
// Check the response type
const contentType = response.headers.get('content-type');
if (hasRequests) {
if (contentType?.includes('text/event-stream')) {
// Handle SSE stream responses for requests
// We use the same handler as standalone streams, which now supports
// reconnection with the last event ID
this._handleSseStream(response.body, { onresumptiontoken }, false);
}
else if (contentType?.includes('application/json')) {
// For non-streaming servers, we might get direct JSON responses
const data = await response.json();
const responseMessages = Array.isArray(data)
? data.map(msg => JSONRPCMessageSchema.parse(msg))
: [JSONRPCMessageSchema.parse(data)];
for (const msg of responseMessages) {
this.onmessage?.(msg);
}
}
else {
await response.body?.cancel();
throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
}
}
else {
// No requests in message but got 200 OK - still need to release connection
await response.body?.cancel();
}
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
get sessionId() {
return this._sessionId;
}
/**
* Terminates the current session by sending a DELETE request to the server.
*
* Clients that no longer need a particular session
* (e.g., because the user is leaving the client application) SHOULD send an
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
* terminate the session.
*
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
* the server does not allow clients to terminate sessions.
*/
async terminateSession() {
if (!this._sessionId) {
return; // No session to terminate
}
try {
const headers = await this._commonHeaders();
const init = {
...this._requestInit,
method: 'DELETE',
headers,
signal: this._abortController?.signal
};
const response = await (this._fetch ?? fetch)(this._url, init);
await response.body?.cancel();
// We specifically handle 405 as a valid response according to the spec,
// meaning the server does not support explicit session termination
if (!response.ok && response.status !== 405) {
throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
}
this._sessionId = undefined;
}
catch (error) {
this.onerror?.(error);
throw error;
}
}
setProtocolVersion(version) {
this._protocolVersion = version;
}
get protocolVersion() {
return this._protocolVersion;
}
/**
* Resume an SSE stream from a previous event ID.
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
*
* @param lastEventId The event ID to resume from
* @param options Optional callback to receive new resumption tokens
*/
async resumeStream(lastEventId, options) {
await this._startOrAuthSse({
resumptionToken: lastEventId,
onresumptiontoken: options?.onresumptiontoken
});
}
}
//# sourceMappingURL=streamableHttp.js.map

View File

@@ -0,0 +1,184 @@
/**
* Experimental client task features for MCP SDK.
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
import { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';
/**
* Experimental task features for MCP clients.
*
* Access via `client.experimental.tasks`:
* ```typescript
* const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });
* const task = await client.experimental.tasks.getTask(taskId);
* ```
*
* @experimental
*/
export class ExperimentalClientTasks {
constructor(_client) {
this._client = _client;
}
/**
* Calls a tool and returns an AsyncGenerator that yields response messages.
* The generator is guaranteed to end with either a 'result' or 'error' message.
*
* This method provides streaming access to tool execution, allowing you to
* observe intermediate task status updates for long-running tool calls.
* Automatically validates structured output if the tool has an outputSchema.
*
* @example
* ```typescript
* const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
* for await (const message of stream) {
* switch (message.type) {
* case 'taskCreated':
* console.log('Tool execution started:', message.task.taskId);
* break;
* case 'taskStatus':
* console.log('Tool status:', message.task.status);
* break;
* case 'result':
* console.log('Tool result:', message.result);
* break;
* case 'error':
* console.error('Tool error:', message.error);
* break;
* }
* }
* ```
*
* @param params - Tool call parameters (name and arguments)
* @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
* @param options - Optional request options (timeout, signal, task creation params, etc.)
* @returns AsyncGenerator that yields ResponseMessage objects
*
* @experimental
*/
async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
// Access Client's internal methods
const clientInternal = this._client;
// Add task creation parameters if server supports it and not explicitly provided
const optionsWithTask = {
...options,
// We check if the tool is known to be a task during auto-configuration, but assume
// the caller knows what they're doing if they pass this explicitly
task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)
};
const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);
// Get the validator for this tool (if it has an output schema)
const validator = clientInternal.getToolOutputValidator(params.name);
// Iterate through the stream and validate the final result if needed
for await (const message of stream) {
// If this is a result message and the tool has an output schema, validate it
if (message.type === 'result' && validator) {
const result = message.result;
// If tool has outputSchema, it MUST return structuredContent (unless it's an error)
if (!result.structuredContent && !result.isError) {
yield {
type: 'error',
error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
};
return;
}
// Only validate structured content if present (not when there's an error)
if (result.structuredContent) {
try {
// Validate the structured content against the schema
const validationResult = validator(result.structuredContent);
if (!validationResult.valid) {
yield {
type: 'error',
error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
};
return;
}
}
catch (error) {
if (error instanceof McpError) {
yield { type: 'error', error };
return;
}
yield {
type: 'error',
error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
};
return;
}
}
}
// Yield the message (either validated result or any other message type)
yield message;
}
}
/**
* Gets the current status of a task.
*
* @param taskId - The task identifier
* @param options - Optional request options
* @returns The task status
*
* @experimental
*/
async getTask(taskId, options) {
return this._client.getTask({ taskId }, options);
}
/**
* Retrieves the result of a completed task.
*
* @param taskId - The task identifier
* @param resultSchema - Zod schema for validating the result
* @param options - Optional request options
* @returns The task result
*
* @experimental
*/
async getTaskResult(taskId, resultSchema, options) {
// Delegate to the client's underlying Protocol method
return this._client.getTaskResult({ taskId }, resultSchema, options);
}
/**
* Lists tasks with optional pagination.
*
* @param cursor - Optional pagination cursor
* @param options - Optional request options
* @returns List of tasks with optional next cursor
*
* @experimental
*/
async listTasks(cursor, options) {
// Delegate to the client's underlying Protocol method
return this._client.listTasks(cursor ? { cursor } : undefined, options);
}
/**
* Cancels a running task.
*
* @param taskId - The task identifier
* @param options - Optional request options
*
* @experimental
*/
async cancelTask(taskId, options) {
// Delegate to the client's underlying Protocol method
return this._client.cancelTask({ taskId }, options);
}
/**
* Sends a request and returns an AsyncGenerator that yields response messages.
* The generator is guaranteed to end with either a 'result' or 'error' message.
*
* This method provides streaming access to request processing, allowing you to
* observe intermediate task status updates for task-augmented requests.
*
* @param request - The request to send
* @param resultSchema - Zod schema for validating the result
* @param options - Optional request options (timeout, signal, task creation params, etc.)
* @returns AsyncGenerator that yields ResponseMessage objects
*
* @experimental
*/
requestStream(request, resultSchema, options) {
return this._client.requestStream(request, resultSchema, options);
}
}
//# sourceMappingURL=client.js.map

View File

@@ -0,0 +1,64 @@
/**
* Experimental task capability assertion helpers.
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
/**
* Asserts that task creation is supported for tools/call.
* Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.
*
* @param requests - The task requests capability object
* @param method - The method being checked
* @param entityName - 'Server' or 'Client' for error messages
* @throws Error if the capability is not supported
*
* @experimental
*/
export function assertToolsCallTaskCapability(requests, method, entityName) {
if (!requests) {
throw new Error(`${entityName} does not support task creation (required for ${method})`);
}
switch (method) {
case 'tools/call':
if (!requests.tools?.call) {
throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
}
break;
default:
// Method doesn't support tasks, which is fine - no error
break;
}
}
/**
* Asserts that task creation is supported for sampling/createMessage or elicitation/create.
* Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.
*
* @param requests - The task requests capability object
* @param method - The method being checked
* @param entityName - 'Server' or 'Client' for error messages
* @throws Error if the capability is not supported
*
* @experimental
*/
export function assertClientRequestTaskCapability(requests, method, entityName) {
if (!requests) {
throw new Error(`${entityName} does not support task creation (required for ${method})`);
}
switch (method) {
case 'sampling/createMessage':
if (!requests.sampling?.createMessage) {
throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
}
break;
case 'elicitation/create':
if (!requests.elicitation?.create) {
throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
}
break;
default:
// Method doesn't support tasks, which is fine - no error
break;
}
}
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1,16 @@
/**
* Experimental task interfaces for MCP SDK.
* WARNING: These APIs are experimental and may change without notice.
*/
/**
* Checks if a task status represents a terminal state.
* Terminal states are those where the task has finished and will not change.
*
* @param status - The task status to check
* @returns True if the status is terminal (completed, failed, or cancelled)
* @experimental
*/
export function isTerminal(status) {
return status === 'completed' || status === 'failed' || status === 'cancelled';
}
//# sourceMappingURL=interfaces.js.map

View File

@@ -0,0 +1,246 @@
/**
* Experimental server task features for MCP SDK.
* WARNING: These APIs are experimental and may change without notice.
*
* @experimental
*/
import { CreateMessageResultSchema, ElicitResultSchema } from '../../types.js';
/**
* Experimental task features for low-level MCP servers.
*
* Access via `server.experimental.tasks`:
* ```typescript
* const stream = server.experimental.tasks.requestStream(request, schema, options);
* ```
*
* For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead.
*
* @experimental
*/
export class ExperimentalServerTasks {
constructor(_server) {
this._server = _server;
}
/**
* Sends a request and returns an AsyncGenerator that yields response messages.
* The generator is guaranteed to end with either a 'result' or 'error' message.
*
* This method provides streaming access to request processing, allowing you to
* observe intermediate task status updates for task-augmented requests.
*
* @param request - The request to send
* @param resultSchema - Zod schema for validating the result
* @param options - Optional request options (timeout, signal, task creation params, etc.)
* @returns AsyncGenerator that yields ResponseMessage objects
*
* @experimental
*/
requestStream(request, resultSchema, options) {
return this._server.requestStream(request, resultSchema, options);
}
/**
* Sends a sampling request and returns an AsyncGenerator that yields response messages.
* The generator is guaranteed to end with either a 'result' or 'error' message.
*
* For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
* before the final result.
*
* @example
* ```typescript
* const stream = server.experimental.tasks.createMessageStream({
* messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
* maxTokens: 100
* }, {
* onprogress: (progress) => {
* // Handle streaming tokens via progress notifications
* console.log('Progress:', progress.message);
* }
* });
*
* for await (const message of stream) {
* switch (message.type) {
* case 'taskCreated':
* console.log('Task created:', message.task.taskId);
* break;
* case 'taskStatus':
* console.log('Task status:', message.task.status);
* break;
* case 'result':
* console.log('Final result:', message.result);
* break;
* case 'error':
* console.error('Error:', message.error);
* break;
* }
* }
* ```
*
* @param params - The sampling request parameters
* @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
* @returns AsyncGenerator that yields ResponseMessage objects
*
* @experimental
*/
createMessageStream(params, options) {
// Access client capabilities via the server
const clientCapabilities = this._server.getClientCapabilities();
// Capability check - only required when tools/toolChoice are provided
if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {
throw new Error('Client does not support sampling tools capability.');
}
// Message structure validation - always validate tool_use/tool_result pairs.
// These may appear even without tools/toolChoice in the current request when
// a previous sampling request returned tool_use and this is a follow-up with results.
if (params.messages.length > 0) {
const lastMessage = params.messages[params.messages.length - 1];
const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
const hasToolResults = lastContent.some(c => c.type === 'tool_result');
const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;
const previousContent = previousMessage
? Array.isArray(previousMessage.content)
? previousMessage.content
: [previousMessage.content]
: [];
const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');
if (hasToolResults) {
if (lastContent.some(c => c.type !== 'tool_result')) {
throw new Error('The last message must contain only tool_result content if any is present');
}
if (!hasPreviousToolUse) {
throw new Error('tool_result blocks are not matching any tool_use from the previous message');
}
}
if (hasPreviousToolUse) {
// Extract tool_use IDs from previous message and tool_result IDs from current message
const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));
const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));
if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {
throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');
}
}
}
return this.requestStream({
method: 'sampling/createMessage',
params
}, CreateMessageResultSchema, options);
}
/**
* Sends an elicitation request and returns an AsyncGenerator that yields response messages.
* The generator is guaranteed to end with either a 'result' or 'error' message.
*
* For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
* and 'taskStatus' messages before the final result.
*
* @example
* ```typescript
* const stream = server.experimental.tasks.elicitInputStream({
* mode: 'url',
* message: 'Please authenticate',
* elicitationId: 'auth-123',
* url: 'https://example.com/auth'
* }, {
* task: { ttl: 300000 } // Task-augmented for long-running auth flow
* });
*
* for await (const message of stream) {
* switch (message.type) {
* case 'taskCreated':
* console.log('Task created:', message.task.taskId);
* break;
* case 'taskStatus':
* console.log('Task status:', message.task.status);
* break;
* case 'result':
* console.log('User action:', message.result.action);
* break;
* case 'error':
* console.error('Error:', message.error);
* break;
* }
* }
* ```
*
* @param params - The elicitation request parameters
* @param options - Optional request options (timeout, signal, task creation params, etc.)
* @returns AsyncGenerator that yields ResponseMessage objects
*
* @experimental
*/
elicitInputStream(params, options) {
// Access client capabilities via the server
const clientCapabilities = this._server.getClientCapabilities();
const mode = params.mode ?? 'form';
// Capability check based on mode
switch (mode) {
case 'url': {
if (!clientCapabilities?.elicitation?.url) {
throw new Error('Client does not support url elicitation.');
}
break;
}
case 'form': {
if (!clientCapabilities?.elicitation?.form) {
throw new Error('Client does not support form elicitation.');
}
break;
}
}
// Normalize params to ensure mode is set for form mode (defaults to 'form' per spec)
const normalizedParams = mode === 'form' && params.mode === undefined ? { ...params, mode: 'form' } : params;
// Cast to ServerRequest needed because TypeScript can't narrow the union type
// based on the discriminated 'method' field when constructing the object literal
return this.requestStream({
method: 'elicitation/create',
params: normalizedParams
}, ElicitResultSchema, options);
}
/**
* Gets the current status of a task.
*
* @param taskId - The task identifier
* @param options - Optional request options
* @returns The task status
*
* @experimental
*/
async getTask(taskId, options) {
return this._server.getTask({ taskId }, options);
}
/**
* Retrieves the result of a completed task.
*
* @param taskId - The task identifier
* @param resultSchema - Zod schema for validating the result
* @param options - Optional request options
* @returns The task result
*
* @experimental
*/
async getTaskResult(taskId, resultSchema, options) {
return this._server.getTaskResult({ taskId }, resultSchema, options);
}
/**
* Lists tasks with optional pagination.
*
* @param cursor - Optional pagination cursor
* @param options - Optional request options
* @returns List of tasks with optional next cursor
*
* @experimental
*/
async listTasks(cursor, options) {
return this._server.listTasks(cursor ? { cursor } : undefined, options);
}
/**
* Cancels a running task.
*
* @param taskId - The task identifier
* @param options - Optional request options
*
* @experimental
*/
async cancelTask(taskId, options) {
return this._server.cancelTask({ taskId }, options);
}
}
//# sourceMappingURL=server.js.map

Some files were not shown because too many files have changed in this diff Show More